Tomcat with Apache2 Virtual Hosts

Using Apache2 with named virtual hosts is standard, but what do you do when you want to put an application on Tomcat behind these hosts?

Thats simple too...

Lets say you have configured two virtual hosts in Apache:

  1. host1.javathinking.com

  2. host2.javathinking.com

and you have two java applications you want running in Tomcat behind these virtual hosts.

To configure Tomcat-5.5.20 with named virtual hosts, update <CATALINA_BASE>/conf/server.xml to look something like this:

<Server port="9281">
<Service name="Catalina">
  <Connector port="9282" proxyPort="80" proxyName="host1.javathinking.com"/>
  <Connector port="9283" proxyPort="80" proxyName="host2.javathinking.com"/>
  <Engine name="Catalina" defaultHost="localhost">
    <Host name="host1.javathinking.com" appBase="webapps/host1">
      <Context path="" docBase="" debug="1"/>
    </Host>
    <Host name="host2.javathinking.com" appBase="webapps/host2">
      <Context path="" docBase="" debug="1"/>
    </Host>
  </Engine>
</Service>
</Server>


Notice how there is a connector for both hosts (using different ports), and each host is configured with context path = "". The applications are deployed to "webapps/host1" and "webapps/host2" but you can change that.

Now, in the Apache configuration for each virtual host I use mod_proxy to forward the requests from Apache to Tomcat using the appropriate port number. Note the security warnings in the Apache documentation about enabling the proxy module.

To enable the proxy modules, use:
sudo a2enmod proxy
sudo a2enmod proxy_http

So inside the virtual host configuration for host1.javathinking.com:
<IfModule mod_proxy.c>
ProxyRequests Off

<Proxy *>
Order deny,allow
Deny from all
Allow from all
</Proxy>

ProxyPass /index.html !
ProxyPass /sitemap.xml !
ProxyPass / http://host1.javathinking.com:9282/
ProxyPassReverse / http://host1.javathinking.com/

</IfModule>

And likewise for host2 but with 9283 as the port number.

Popular posts from this blog

Slow, Buffering, Stuttering Udemy Video

Intellij tip - Joining multiple lines into one

Looking for IT work in Australia? JobReel.com.au!