Tomcat – Pretty URLs when using Tomcat behind an Apache proxy

apache-2.2rewritetomcat

We have Tomcat 5.5 running behind and Apache 2.2 mod_proxy. We would like prettier URLs. For example, this is more or less how our URLs look now:

http://example.com/foo/app/home   (home page)
http://example.com/foo/app/bar    (other parts of the web app)
http://example.com/foo/api/qux    (API hooks)
http://example.com/foo/quux       (misc)

We would like the publically exposed URLs to be simpler, e.g.:

http://example.com/         (home page)
http://example.com/bar      (other parts of the web app)
http://example.com/api/qux  (API hooks)
http://example.com/quux     (misc)

I know how to have Apache rewrite the incoming URLs into the longer ones Tomcat uses, but I'm concerned that this might confuse Tomcat. I am reasonably experienced with Apache but a Tomcat newbie.

Also, we want to do this with rewriting, not redirects (e.g., http://example.com/ should not simply redirect to http://example.com/foo/app/home), as we want to keep the ugly URLs out of the address bar entirely.

Best Answer

If you're rewriting everything to a common location, you would typically do something like this:

ProxyPass        / http://localhost:8080/foo/
ProxyPassReverse / http://localhost:8080/foo/

If you need different rules for different paths, you would probably use the Proxy flag on a series of RewriteRules:

RewriteRule /bar/(.*) http://localhost:8080/foo/app/bar/$1 [P]
RewriteRule /api/qux/(.*) http://localhost:8080/foo/api/qux/$1 [P]
RewriteRule /quux/(.*) http://localhost:8080/foo/quux/$1 [P]
RewriteRule /(.*) http://localhost:8080/foo/app/$1 [P]

The this will send things to the appropriate place in Tomcat.

The only complication is if the application dynamically generates URLs with fully qualified paths. In this case, you need to either fix the application, or use something like mod_proxy_html to rewrite links in your HTML content.