Using Apache Front-End with Tomcat for JSP
Tuesday, 12 August 2008 00:00

In a previous post, we discussed how it's possible to use Apache as a reverse proxy to offload SSL and GZip compression from a Tomcat (or similar) J2EE server. Originally, we had set this up on Windows, but we have since moved it over to Ubuntu with no problems.

Another useful setup is to use Apache to serve up your static resources (such as images, javascript files, and CSS sheets), while only sending JSP or servlet requests over to Tomcat. This can be useful because Apache is generally much faster at serving up static content, not to mention that you remove any extra overhead of proxying these requests. Even better, you can continue to use Apache to handle SSL and compression.

This tutorial assumes that you've been able to get Apache and Tomcat up and running independently, and we'll walk through how to connect them.

First Attempt: Proxying All Traffic
Remember from our previous post, you simply need to use the Location tag in your Apache config file to proxy requests over to Tomcat. (For us, this configuration file is located at /path/to/apache2/sites-enabled/000-default, but this could vary based on your setup.)

<VirtualHost>
...
<Location />
ProxyPass http://appserver:8080/
ProxyPassReverse http://www.domain.com/
</Location>
...
</VirtualHost>

Real Attempt: Proxying JSP/Servlet Traffic
All we need to do is slightly modify this configuration so that it will only proxy JSP or servlet traffic, rather than all traffic:

<VirtualHost>
...
<Location /path/to/servlet>
ProxyPass http://appserver:8080/path/to/servlet
ProxyPassReverse http://www.domain.com/path/to/servlet
</Location>
...
</VirtualHost>


If your JSP files aren't all in the same directory, you could also use the LocationMatch tag to match files ending with .jsp. Keep in mind that LocationMatch uses a regular expression, which might look something like this:

<LocationMatch .+\.jsp$>
ProxyPass http://appserver:8080/
ProxyPassReverse http://www.domain.com/
</Location>

Conclusion
Assuming the remainder of your Apache was already correctly setup, that should be all there is to it. Apache will serve up most files itself, but will use Tomcat where the Location or LocationMatch tags are matched.

A special note: This tutorial was proxying to Tomcat using HTTP, but you could also use the AJP connector. AJP is a binary protocol which should reduce the amount of data that needs to be transferred between Apache and Tomcat. To do this, make sure that mod_proxy.so and mod_proxy_ajp.so are loaded, then simply tweak the ProxyPass directive:

ProxyPass ajp://appserver:8080/