Thursday 4 April 2013

How to configure IIS 7 to redirect non-www domain to www domain?

One of few legacy leftovers that was never dropped over the years is the common use of www domain prefix. It is not a problem per se for us humans, but SE bots have mind of their own. When traversing a non-www and a www version of a web site, apparently, google and other bots are treating them as two separate web entities, even if content is identical.

This causes confusion in SE databases and in a worst case a drop from the index.
To avoid this confusion, web site operators should redirect their non-www traffic to www version of the website, or redirect the www version to the non-www version of the site.

This should be done using 301 redirect, i.e. when request for http://example.com is made, the web server would return

HTTP/1.1 301 Moved Permanently
Location: http://www.example.com/


response with the location of the new site.


So how can I do this in IIS 7? Well, you have to edit web.config file, modify or add
the following section to its rewrite section.


<rewrite>
   <rules>
      <rule name="non www to www" enabled="true">
         <match url="(.*)" />
         <conditions>
            <add input="{HTTP_HOST}" negate="true" pattern="^www\.([.a-zA-Z0-9]+)$" />
         </conditions>
         <action type="Redirect" url="<a href="http://www.{HTTP_HOST}/{R:0"
>http://www.{HTTP_HOST}/{R:0</a>}" appendQueryString="true" redirectType="Permanent" />
      </rule>
   </rules>
</rewrite>
 
This should be your first rule.

The rewite section should be placed in system.webServer section.

Then just refresh your site and voila you have all trafic to http://example.com/* redirected to http://www.example.com/*

1 comment:

  1. Thank you for this post, it guided me to the right direction. One comment is that you need "URL Rewrite" module installed for this to work. otherwise you see a 500 internal error...

    Kind Regards!

    ReplyDelete