apache2, tomcat and mod_proxy

Making Tomcat work with a web server is a lot easier than it used to be, but that isn’t saying a whole lot. There are quite a number of questions about this on the web, so hopefully my experience will be helpful to someone.

I needed to link Apache 2 to Tomcat 5.5 on a Debian box. There are two general methods used for this: mod_jk or mod_proxy. There are variations, but these are the usual suspects. Also in general, mod_jk is considered the faster option (though as a third alternative a standalone Tomcat instance will do the job quite well - if you don’t require anything but Java).

I tried to use JK by downloading and compiling it, however apxs2 isn’t installed and apt-get refused to install apache2-threaded-dev (apparently a broken package as some dependencies were out of whack). So mod_proxy was it.

I found these instructions (kindly translated by Babelfish), which gave me the general idea, and later the Tomcat docs themselves brought forth the Proxy HOW-TO, which is a useful, step-by-step guide.

Based on the steps in the above guides, I used the following configuration:

  • mod_proxy configured for reverse proxying:
        # reverse proxy
        ProxyRequests Off
    
        # allow proxying of all requests;
        # don't turn ProxyRequests On with this configuration!
        <Proxy *>
          Order deny,allow
          Allow from all
        </Proxy>
  • Rewrite rules in VirtualHost definition:
        #tomcat rewrite/proxy directives
        <IfModule mod_rewrite.c>
            RewriteEngine On
            RewriteLog "/var/log/apache2/rewrite.log"
            RewriteLogLevel 1
            RewriteRule ^/url-path/(.*) http://localhost:8081/context-path/$1 [P]
        </IfModule>

    Note url-path is the path that will be redirected, context-path is the Tomcat context, and 8081 is assumed to be the port your proxied Tomcat HTTP connector is listening on.

    Note also that the rewrite rule is such that a request for http://meh.com/foo would fail, but http://meh.com/foo/ would succeed. There is probably a way around this, using a slightly different regex, but I haven’t taken the time.

    The Tomcat docs detail different directives; I’ve seen fragments on the web saying that these don’t rewrite headers properly, but I’ve yet to work out the details of this.

  • In Tomcat’s server.xml, the connector includes the proxy attributes:

After reloading Apache and restarting Tomcat it all appears to work. I would like to work out how to get mod_jk working at some point though - and perhaps (if I have a weekend to spare) getting the latest Apache to work with its newer connector modules. Enabling SSL is another job that will happen somewhere along the line too.

An interesting side-note to this connection method is the possible impact on caching, as Nick found out. I don’t think this will affect me much at this point, but it’s worthwhile keeping it in mind.

Comments are closed.