regextomcaturl-rewritingtomcat-valve

Re-writing tomcat 8 urls


I have two tomcat applications deployed under two different contexts:

someurl.com/context1/
someurl.com/context2/

I need to intercept urls in the form:

someurl.com/clientname/context1/ 

and redirect them to url:

someurl.com/context1/clientname

where "clientname" is dynamic

I have tried using a rewrite valve in the element of my tomcats server.xml file, but it still works only for urls which include the context. i.e.:

someurl.com/context1/clientname/context1 

gets re-written to

someurl.com/context1/clientname

using the following regex:

RewriteCond %{REQUEST_URI}  ^.*/context1/.*$

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

Is there a way to globally re-write urls in such a way that the context is not taken into account?


Solution

  • After a lot of digging around I found out a really easy way of achieving the desired result. The trick is to set up a root context without any actual application being deployed there. Then to that root context a RewriteValve is added like this:

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

    It is important that the crossContext is set to true, so the root context can communicate with the lower level contexts.

    Then in WEB-INF of the root context the following rewrite.config will do the trick:

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

    which basically means: capture all ur's which have the form: clientname/context1/etc and route them to context1/clientname/etc