Redirect Non www to www using UrlRewriteFilter in Web Servers

On apache servers usually we redirect by modifying .htaccess file. But it doesn’t work on web apps that are hosted on servers like tomcat, jboss etc. So in this case we’ll use a Java Web Filter called UrlRewriteFilter. It allows us to change url before they hit the apis. It is compatible with all web servers (Apache Tomcat, JBoss, Jetty etc.). Its licence is BSD-3-Clause

If you want the latest jar then you can take the latest pull from its github repository and compile it using command mvn clean install.

So lets start ::

1. If you webapp is a maven webapp then add the dependency to your pom.xml


Otherwise download the jar file directly from maven repository and add in your webapp.

2. Now add this code in your WEB-INF/web.xml


3. Create urlrewrite.xml in WEB-INF directory (same place as web.xml). Paste the following code in it.

    <name>seo redirect</name>
    <condition name="host" operator="notequal">^</condition>
    <to type="permanent-redirect" last="true">/$1</to>

Don’t forget to change the website name. That’s it.


Leave a Reply

Your email address will not be published. Required fields are marked *