Monday, March 21, 2011

Automatically Add “www” to your site on Tomcat or: Canonical Hostnames

Sometimes we would like that our website domain will always contain “www”.

I can this of two good reasons (beside of making all your site’s urls neat and unified) for adding “www” to your site urls:

  • To avoid cookie issues: Cookies are being stored for domains. www.example.com and example.com are 2 different domains when it comes to cookies. So if you would like to store some data in a cookie without wondering where did it disappear. Unify all the urls of your site to contain “www” and you are always working on the same domain.
  • To avoid security issues: Sometimes we would like to do some JavaScript coding on our site that may require us to be on the same domain (for example: running some JavaScript code from an iFrame on the parent window). Since url with “www” and url without “www” is considered to be a different domain, by making sure all of our urls contain the “www” prefix, we make sure we will not fall in all kind of cross domain security traps.

So, how do we make sure all our urls will always contain the “www” prefix" on Tomcat?

Luckily for us there is a great Java open source project named tuckey that can easily help us to accomplish that task. Tuckey is Url rewrite filter. It rewrites our urls according to set of predefined rules. As you noticed tuckey is doing much more than just adding “www” to our urls, but this is not for the scope of this post. You can learn more about tuckey and download it from this web site: http://www.tuckey.org/.

After you download and install tuckey on your web application (it is well details on the tuckey web site how this thing can be done), you simply have to add this rule to you urlrewrite.xml file:

<rule>
  <name>Canonical Hostnames</name>
  <condition name="host" operator="notequal">^www.mydomain.com</condition>
  <condition name="host" operator="notequal">^$</condition>
  <from>^/(.*)</from>
  <to type="redirect" last="true">http://www.mydomain.com/$1</to>
</rule>

Make sure that this rule is the first rule on your urlrewrite.xml file.

3 comments:

  1. It does n't work for me. I have when the type is https and site name is not prefixed with www it checks https://site.com instead of https://www.site.com. My site configure to go to https when http is hit, with tomcats web.xml as below:


    Protected Context
    /*


    CONFIDENTIAL

    ReplyDelete
  2. Does this rule is the first on your list?

    ReplyDelete