Rewrite

HowTo: Enable URL rewite for tomcat or other servlet container

Posted on Updated on

It is a URL rewrite feature which is most similar to the apache mod_rewrite, we can use the similar rules to apply the rewrite. Ensure that the ‘UrlRewriteFilter‘ JAR file is on your web-application’s classpath.  place the JAR file in your webapp under ‘/WEB-INF/lib’ will do the trick, and if you’ve spent any time at all working with webapps you probably already have a preferred way of doing this. Alternately, you may want to install the JAR file in your servlet container’s ‘/lib’ folder, particularly if you are deploying multiple webapps on your server and you want to have ‘UrlRewriteFilter‘ available to any/all of them automatically.

Download JAR from here

Read more Examples

once you have the ‘UrlRewriteFilter‘ JAR on your webapp’s classpath, the real setup can begin. Open your application’s ‘web.xml‘ file, and add the following filter configuration to your webapp

<filter>
 <filter-name>UrlRewriteFilter</filter-name>
 <filter-class>org.tuckey.web.filters.urlrewrite.UrlRewriteFilter</filter-class>
 <init-param>
 <param-name>logLevel</param-name>
 <param-value>WARN</param-value>
 </init-param>
<init-param>
 <param-name>confPath</param-name>
 <param-value>/WEB-INF/urlrewrite.xml</param-value>
 </init-param>
</filter>
 <filter-mapping>
 <filter-name>UrlRewriteFilter</filter-name>
 <url-pattern>/*</url-pattern>
 </filter-mapping>

This will make the serverlet container to redirect the traffic to UrlRewriteFilter.  Note that although it is not discussed on the official site, that ‘logLevel‘ parameter is absolutely essential for filter to be apply for the traffic.

If you finish adding the tags in web.xml, then move to create urlrewrite.xml in the same directory as with the web.xml. Configure the example rules  for  the URL rewrite.

<?xml version="1.0" encoding="utf-8"?>
 <!DOCTYPE urlrewrite PUBLIC "-//tuckey.org//DTD UrlRewrite 3.2//EN"
 "http://tuckey.org/res/dtds/urlrewrite3.2.dtd">
 <urlrewrite>
  <rule>
        <name>Domain Name Check</name>
        <condition name="host" operator="notequal">www.server.com</condition>
        <from>^(.*)$</from>
        <to type="redirect">http://www.server.com/$1</to>
    </rule>
    <rule>
        <from>/test</from>
        <to type="redirect">%{context-path}/examples</to>
    </rule>
</urlrewrite>

The first rule is for any request tot he application with IP or alternative alias Domain name added in the server has to rewrite to server.com. It can be also use to rewite for including www. in the URL .

The second rule is for the redirect the invalid application “test” to  to the examples,

Its looks like this :  http://test.com/test   –>  http://www.server.com/examples/  . Both the test.com and server.com are in the same server and same webapps