Skip to content

Tomcat9 RewriteValve Usage

Suppose you have a Tomcat based servlet container with webapps directory name “ORIGINAL”, and then you have a reason to rename it as “MOVED”:

  • /ORIGINAL/servlet/path
  • /MOVED/servlet/path

You have a few ways to handle this, but simplest turned out to be rewriting the HTTP URL path in Tomcat’s request pre-processing phase invoking Valves.  (Assuming you have at least Tomcat 8.5 for working RewriteValve.)

Create a ROOT webapp; create following directory and file structure inside your Tomcat server.  The “ROOT” name in all uppercase is special allowing this mapping to affect full HTTP URL path, instead of only inside a given servlet.

  • server/webapps/ROOT/
  • server/webapps/ROOT/META-INF/context.xml
  • server/webapps/ROOT/WEB-INF/rewrite.config

The context.xml contains following:

<?xml version="1.0" encoding="UTF-8"?>
<!-- This goes to /META-INF/context.xml -->
<Context reloadable="false"
         swallowOutput="true"
         unpackWAR="false"
         processTlds="false">

    <Valve className= "org.apache.catalina.valves.rewrite.RewriteValve" />
</Context>

And the rewrite.config  define URL mappings:

##
## This runs in ROOT context path 
##    (  = "/" ) of the URL
## 

RewriteCond  %{REQUEST_PATH}  ^/ORIGINAL/.*
RewriteRule ^/ORIGINAL/(.*)$  /MOVED/$1 [L,NE]

This mechanism has complicated capability for mapping and regular expression rewriting of the URL paths. Those are simpler thing to master once you get the configuration in place. See Tomcat documentation at: https://tomcat.apache.org/tomcat-9.0-doc/rewrite.html

Additional Notes:

In principle this rewritter should also work in server.xml in <Host> context, but it is easier to create special “ROOT” webapp.

What happens if you try to do this in your webapp that is not named “ROOT”? The rewrite works, but receives only paths with the webapp path prefix removed, and rewriting will not be able to direct the caller to other webapp context.

What you can use this for includes:

  • Aliasing web service URL paths (give service without reporting redirect)
  • Moving web service URL paths (report a redirect to the caller)
  • “Fixing” an URL bug in popular 3rd party client library
  • Creating URL compatibility mappings against older version of the service, or different implementations

Hint: If you are uncertain regarding the configuration file being read, you can put there a line starting with unknown keyword ( like “break-it” ), then your Tomcat will not restart, and it will hopefully report some error. Now you do see evidence that the configuration file is being read – it is in correct location. Remove the broken input line.

Hint: Use of logging.properties works better if you do not have swallowOutput=”true” in any of your context.xml files defining the <Context ..> elements.

Publish Date: 16 May 2022
Written and Edited by: Matti Aarnio