Configuring Tomcat's Rewrite Valve To Work With Different Contexts

Imagine you have a Tomcat 8 server running two different contexts with URLs like this:


and you need to capture requests to:


where clientname is dynamic, and you'd like to redirect those requests to:


Normally you can use Tomcat's RewriteValve to rewrite URLs, but the RewriteValve is configured in the Context element of Tomcat's configuration xml file. This means it will only work for URLs under the context (e.g. someurl.example/context1/thingsaffectedbyrewrite).

The solution to this is surprisingly simple. All that needs to be done is to have an empty ROOT context in Tomcat (without any deployed applications in it) with the following configuration:

<?xml version='1.0' encoding='utf-8'?>
<Context docBase="ROOT" path="/" reloadable="true" crossContext="true">
    <Valve className="org.apache.catalina.valves.rewrite.RewriteValve"/>

This is the content of the context.xml file that needs to be in your Tomcat webapps directory under the ROOT/META-INF/ directory. The only other thing that is necessary is to have a rewrite.config file in the ROOT/WEB-INF directory in Tomcat webapps directory, with the following contents:

RewriteRule ^/.*/context1/(.*)$     /context1/$1    [L]

This is the configuration for the RewriteValve and describes the actual URL rewriting via regex as explained in the documentation.

comments powered by Disqus