Archive for the Apache Tomcat Category

How to configure virtual hosts on Tomcat

Posted in Apache Tomcat with tags , , , on July 1, 2008 by vinaychilakamarri

With virtual hosts, you can serve different domain names on a single instance of Tomcat server. I will be describing the way to do this on this post.

To open a virtual host on Tomcat you need to do three things:

1. Create a appBase for each virtual host you will be adding
2. Edit the server.xml to add the virtual hosts
3. Edit the etc/hosts file to loopback on the virtual hosts

1. Creating an appBase is a very important step for our process. This is like creating multiple “webapps” directories for every virtual host that we have. Every appBase should contain a “ROOT” directory, which will contain all the stuff that we will be needing for providing on a virtual host. This can be servlets, html files, etc etc. Put anything you want to host, in that directory. So this will be the structure of your appBase directory after you complete the above step:

2. Server.xml tells the Tomcat server about the details of the virtual hosts. You can locate the server.xml file under conf directory of Tomcat. Find the following in the server.xml:

– <Engine name=”Catalina” defaultHost=”localhost”>

To this part, we should add our virtual hosts. Here is the way to do it:

– <Engine name=”Catalina” defaultHost=”vinay.com”>
<Host name=”vinay.com” appBase=”vinayapps” />
<Host name=”chilakamarri.com” appBase=”chilakapps” />

Make sure that the defaultHost is one of the hosts that you defined in the Host tags. This will complete the configuration that is needed on the Tomcat, to run virtual hosts. But there is another important step that you need to perfom, to tell the browser (client) that it has to loop back to the local machine when you type in the URL that you just created. This is easy

3. In the final step, we should tell our client to connect to loop back to the localhost when we type in the virtual host name. This is a very easy step.

on Windows:
%root%:\WINDOWS\system32\drivers\etc and locate the “hosts” file in that. Edit the hosts file to something like this:

127.0.0.1 vinay.com
127.0.0.1 chilakamarri.com
This will tell the machine that it has to loop back on the above domain. You can access the above domain only on the ports that you opened on the localhost. For example, the Tomcat comes with a default 8080 port connnector. To create multiiple connectors do this:
a. Open server.xml in your fav editor.
b. Find a tag like this on the xml file: <Connector port=”8080″ protocol=”HTTP/1.1″ connectionTimeout=”20000″ redirectPort=”8443″ />
c. Add another tag of that sort, now with your custom port. Ex: <Connector port=”666″ protocol=”HTTP/1.1″ connectionTimeout=”20000″ redirectPort=”8443″ />

Voila! you now have your virtual hosts on your favorite ports! Remember that opening a connector will expose all the appBases on the server.

Advertisements