Tomcat & Apache Reverse Proxy

I have to admit Apache HTTPD has one of the most confusing documentation among other tools out there. Here are my Apache & Tomcat requirements:

  • A domain name pointing to my hosting server
  • Tomcat running on http://localhost:8080 on my hosting (default)
  • Apache HTTP server running on http://localhost:80 on hosting (default)
  • Request to should be reverse proxied into Tomcat without the end-user noticing the port difference

After 2 hours of reading documentation, trial and error, I managed to get this setup working using following Apache Reverse Proxy and VirtualHost configuration:

<VirtualHost *:80>
   ProxyPass        / http://localhost:8080/
   ProxyPassReverse / http://localhost:8080/
   ProxyPassReverseCookieDomain localhost
   ProxyPreserveHost On

Configuration Explained

  1. ProxyPass directive will cause request to (and any other paths) be internally forwarded to http://localhost:8080/foo/bar. Internally here means the user will never know — it will look as if the response came from Behind the screen (on the server) Apache forwards the request and obtain the response to/from Tomcat. The trailing slash (/) at the end of http://localhost:8080/ is important because without it request to will be internally translated to http://localhoststyle.css (which is wrong).
  2. ProxyPassReverse directive is useful when Tomcat sends HTTP 3xx redirect response. If Tomcat redirects http://localhost:8080/logout into http://localhost:8080/login, your end user will see http://localhost:8080/login unless you place this directive.
  3. ProxyPassReverseCookieDomain directive will cause the cookie domain be re-written into the intended domain. Without this end-user would see localhost as their cookie domain (which is again wrong).
  4. ProxyPreserveHost directive will cause the domain header be forwarded into Tomcat. Without this Tomcat will see the incoming request coming from localhost. This is handy when you’re planning to serve multiple host name under Tomcat.

You can try this on be adding the above configuration into your httpd.conf file (typically located on /etc/httpd/conf/httpd.conf). Once you’ve edited the config, restart apache using sudo apachectl -k restart command.


One thought on “Tomcat & Apache Reverse Proxy

  1. Pingback: Useful Apache Configuration | Otherwise I'll Forget!

Leave a Reply

Please log in using one of these methods to post your comment: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s