In this post you will learn how to configure virtual hosting on Tomcat 7. It works also well if you use Apache as a frontend with mod_proxy_ajp (see my previous post).

In this example www.myfirstapp.com will use the webapp myfirstapp.war and www.mysecondapp.com will use the webapp mysecondapp.war. Let’s see.

First add the new hosts in server.xml (after default localhost host):

<Host name="localhost"  appBase="webapps" unpackWARs="true" autoDeploy="true">
        <Valve className="org.apache.catalina.valves.AccessLogValve" directory="logs"
               prefix="localhost_access_log." suffix=".txt"
               pattern="%h %l %u %t &quot;%r&quot; %s %b" />

</Host>

<Host name="www.myfirstapp.com" appBase="webapps/myfirstapp" unpackWARs="true" autoDeploy="true">
                 <Valve className="org.apache.catalina.valves.AccessLogValve" directory="logs"
                        prefix="myfirstapp_access_log." suffix=".txt"
                        pattern="%h %l %u %t &quot;%r&quot; %s %b"/>
</Host>

<Host name="www.mysecondapp.com" appBase="webapps/mysecondapp" unpackWARs="true" autoDeploy="true">
                 <Valve className="org.apache.catalina.valves.AccessLogValve" directory="logs"
                        prefix="mysecondapp_access_log." suffix=".txt"
                        pattern="%h %l %u %t &quot;%r&quot; %s %b"/>
</Host>

 

Then configure context for myfirstapp:

cd /opt/apache-tomcat-7.0.34/conf/Catalina/
mkdir www.myfirstapp.com
cd www.myfirstapp.com
vi ROOT.xml

The file used is « ROOT » because it is the name required for the application to be deployed in the context path « / ».
The .war deposited in the AppBase must therefore be called « ROOT.war ».

# Content of ROOT.xml
<Context path=""/>

 

Do the same for mysecondapp:

cd /opt/apache-tomcat-7.0.34/conf/Catalina/
mkdir www.mysecondapp.com
cd www.mysecondapp.com
vi ROOT.xml
# Content of ROOT.xml
<Context path=""/>

 

Deploy your webapps:

cp myfirstapp.com /opt/apache-tomcat-7.0.34/webapps/myfirstapp/ROOT.war
cp mysecondapp.com /opt/apache-tomcat-7.0.34/webapps/mysecondapp/ROOT.war
service tomcat start

 

You can now access your webapps http://www.myfirstapp.com:8080 and http://www.mysecondapp.com:8080.
To see how to access it on port 80 with Apache and mod_proxy_ajp see my previous post on this topic.

That’s all folk

Source 1 (en) : http://wiki.magnolia-cms.com/display/WIKI/Tomcat+virtual+hostsSource 2 (en) : http://tomcat.apache.org/tomcat-7.0-doc/config/host.html#Automatic_Application_Deployment