天天看点

在 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/