Virtual Hosting – Tomcat 7

Often we need to host applications with different domain names in a single instance of application server or on a single IP address, then same we can do it using Virtual Hosting.

Virtual hosting is a method for hosting multiple domain names (with separate handling of each name) on a single server (or pool of servers).

In this post, we will study how we can do Virtual Hosting in Tomcat 7.

Before, starting with Virtual hosting, let’s understand Catalina Engine in server.xml present in a directory apache-tomcat-7.0.64/conf:

<Engine name="Catalina" defaultHost="localhost">
 
 <Realm className="org.apache.catalina.realm.LockOutRealm">
  <Realm className="org.apache.catalina.realm.UserDatabaseRealm"
 resourceName="UserDatabase"/>
 </Realm>
 
 <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>

</Engine>

<Engine> tag specified above refers to engine which is responsible for executing servlet. Here Catalina is the Engine.

<Host> tag specified above is the domain name and web apps base location is where the application is present. Here localhost is the domain name and appBase is the webapps folder under apache-tomcat-7.0.64 server.

Now we will create 2 more <Host> enteries under the Catalina Engine, one with http://www.arpit-virtual-host.com as domain name and appBase as webapps_com and another one with http://www.arpit-virtual-host.in domain name and appBase as webapps_in under apache-tomcat-7.0.64 server.

<Host name="www.arpit-virtual-host.com" appBase="webapps_com"
 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.arpit-virtual-host.in" appBase="webapps_in"
 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>

Now deploy the websites to respective webapps folder and start the tomcat.

Next, open the /etc/hosts file through root privilege and add below entries:


127.0.0.1 www.arpit-virtual-host.in
127.0.0.1 www.arpit-virtual-host.com