Routing Non-www to www Domain and Vice Versa Using IIS URL Rewrite

If you have a domain and you want to refer to it in a single way, either with or without www, then you can use IIS URL Rewrite to redirect requests.

IIS URL Rewrite is a module that supports configurations from your web.config file to manipulate URLs. With it you can easily redirect from a non-www domain to a www domain.

You might think that yourwebsite.com looks shorter and cleaner and I would agree of course, however if you want to strive for a high-performance website you must reconsider.

When you use a non-www domain you are putting cookies on the all catching domain. In other words, for each static image on your website you would also be serving a huge session cookie along with it. The good side of using www is that you can isolate cookies in this subdomain and have a separated subdomain (cookie free and heavily cached) to serve static content.

    www.yourdomain.com
    static.yourdomain.com

Jeff Atwood (Stack Overflow co-founder) once posted:

    WARNING: If you pick the domain example.com, be aware that all cookies you store on that domain will be sent to all subdomains … forever. This is a major downside I didn't discover until years later and it's big enough to make me regret choosing stackoverflow.com versus http://www.stackoverflow.com.

Stack Exchange overcame this issue by creating a dedicated domain to serve static content only.

Enough with talk, let's get to the code. Once you have the module installed you can just add on your web.config under the system.webServer tag as in the following:

To convert non-www to www* be sure to update the domain suffix as in the following:
  1. <rewrite>    
  2.   <rules>    
  3.     <rule name="Canonical" stopProcessing="true">    
  4.       <match url=".*" />    
  5.       <conditions>    
  6.         <add input="{HTTP_HOST}" pattern="^([a-z]+[.]com)$" />    
  7.       </conditions>    
  8.       <action type="Redirect" url="http://www.{C:0}/{R:0}"    
  9.           redirectType="Permanent" />    
  10.     </rule>    
  11.   </rules>    
  12. </rewrite> 
To convert a www to a non-www:
  1. <rewrite>    
  2.   <rules>    
  3.     <rule name="Canonical" stopProcessing="true">    
  4.       <match url=".*" />    
  5.       <conditions>    
  6.         <add input="{HTTP_HOST}" pattern="^www[.](.+)" />    
  7.       </conditions>    
  8.       <action type="Redirect" url="http://{C:1}/{R:0}"    
  9.           redirectType="Permanent" />    
  10.     </rule>    
  11.   </rules>    
  12. </rewrite>   

Up Next
    Ebook Download
    View all
    Learn
    View all