Saturday, September 21, 2013

Rule for URL rewrite module for redirecting from no www to www address without using domain name

In one of my previous articles (see Several useful SEO rules via IIS URL rewrite module) about URL rewrite IIS module I showed how to add a rule which will redirect users from address with no www prefix to the address with www:

   1: <rule name="redirect_from_nowwww_to_www" enabled="true" stopProcessing="true">
   2:   <match url=".*" />
   3:     <conditions>
   4:       <add input="{HTTP_HOST}" pattern="^example\.com$" />
   5:     </conditions>
   6:   <action type="Redirect" url="http://www.example.com/{R:0}"
   7: appendQueryString="true" redirectType="Permanent" />
   8: </rule>

It works, but it contains domain name (example.com) which makes it specific to particular site. You can’t just copy and paste it to another web.config: in this case you will need to change the values to new host header.

Here is the more universal implementation of the same rule:

   1: <rule name="redirect_from_nowwww_to_www" enabled="true" stopProcessing="true">
   2:   <match url=".*" />
   3:   <conditions>
   4:     <add input="{HTTP_HOST}" pattern="^(www\.)(.+)$" negate="true" />
   5:   </conditions>
   6:   <action type="Redirect" url="http://www.{HTTP_HOST}/{R:0}"
   7: appendQueryString="true" redirectType="Permanent" />
   8: </rule>

Here I used possibility to add negative conditions (host doesn’t match to www pattern on line 4) and possibility to use server variables in actions ({HTTP_HOST} in action url on line 6). It will work like 1st rule, but can be used as is on any site accessed by http (in order to make it work for https, change http to https on line 7. Note also that in real implementation lines 6 and 7 should be on the single line).

No comments:

Post a Comment