天天看點

在 Tomcat 上配置虛拟主機

在 Tomcat 上配置虛拟主機

轉載:

一 準備

我們将配置兩台虛拟主機,假設域名分别為

www.sentom1.net

www.sentom2.net

為了測試友善,請在客戶機的:

Win2K://WINNT/system32/drivers/etc/hosts

Linux:/etc/hosts

檔案中增加下面内容,然後檢查一下這兩個域名是否解析正确。

192.168.0.1	www.sentom1.net
	192.168.0.1	www.sentom2.net

      
當然,在生産環境中這樣做是不行的,需要的在 DNS 上做相應的域名解析。

二 Tomcat安裝

Tomcat 的安裝不在本文的讨論範圍,請參考 這裡。請確定Tomcat安裝正确,不然請不要繼續進行下面的配置步驟。

将 tomcat 目錄下的 webapps 目錄在同一目錄複制一份,目錄名分為 webapps2 ,然後将 webapps 目錄改名 為 webapps1 。最後 tomcat 的目錄結構大緻如下:

tomcat
	   |--bin
	   |--common
	   |--conf
	   |--logs
	   |--server
	   |--shared
	   ......
	   |--webpapps1
	   |--webpapps2
	   |--work

      
最後,寫一個簡單 html 檔案用于測試,檔案名為 test.html ,檔案内容如下:
<HTML>
<HEAD>
<TITLE>測試</TITLE>
</HEAD>

<BODY>
<P align="center">你現在通路的是 <FONT COLOR="#FF0000">www.sentom1.net</FONT></P>
</BODY>
</HTML>
      

将 test.html 檔案分别在 tomcat/webapps1/ROOT、tomcat/webapps2/ROOT 目錄放置一份,然後将 tomcat/webapps2/ROOT/test.html 檔案内容中“www.sentom1.net”改為“www.sentom2.net”。

至此,前期的準備工作做完了,全是一些體力活。

三 配置虛拟主機

前面提到了獨立 IP 和共享的 IP。本文介紹的是共享的 IP 模式,這種模式就是所有的虛拟主機都使用同一 IP 。目前國内 IDC 提供的虛拟主機都是這種模式。這種模式的優點是節約數量有限的 IP ,缺點就是虛拟主 機隻能通過域名通路而不能通過 IP 通路(其實也不算是缺點,隻對郵件系統中使用者的通路方式有一點點影響 )。而另外一種獨立 IP 模式主要應用在郵件服務中,這裡就不做介紹了。

配置 www.sentom1.net 虛拟主機

打開 tomcat/conf/server.xml 檔案,将 Host 元素之間的内容全部删掉,然後把下面内容加如到 Host 元素 原來的位置。

<Host name="www.sentom1.net" debug="0" appBase="webapps1"
             unpackWARs="true" autoDeploy="true">
       
        <Valve className="org.apache.catalina.valves.AccessLogValve"
                 directory="logs"  prefix="sentom1_access_log." suffix=".txt"
                 pattern="common" resolveHosts="false"/>

        <Logger className="org.apache.catalina.logger.FileLogger"
                 directory="logs"  prefix="sentom1_log." suffix=".txt"
                 timestamp="true"/>

      </Host>
      

配置 www.sentom2.net 虛拟主機

将下面内容追加到 Host 元素後面,注意 Host 元素中 name 屬性和 appBase 屬性的值的變化。

<Host name="www.sentom2.net" debug="0" appBase="webapps2"
             unpackWARs="true" autoDeploy="true">
       
        <Valve className="org.apache.catalina.valves.AccessLogValve"
                 directory="logs"  prefix="sentom2_access_log." suffix=".txt"
                 pattern="common" resolveHosts="false"/>

        <Logger className="org.apache.catalina.logger.FileLogger"
                 directory="logs"  prefix="sentom2_log." suffix=".txt"
                 timestamp="true"/>

      </Host>
      

現在可以啟動 Tomcat 了,分别通路

http://www.sentom1.net:8080/test.html

http://www.sentom2.net:8080/test.html

如果通路得到的頁面内容分别是下面的内容,那表明虛拟主機已經配置成功了。否則,請檢查你的配置過程并 重新按照文檔配置。

四 參考

http://jakarta.apache.org/tomcat/