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.
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:
- <rewrite>
- <rules>
- <rule name="Canonical" stopProcessing="true">
- <match url=".*" />
- <conditions>
- <add input="{HTTP_HOST}" pattern="^([a-z]+[.]com)$" />
- </conditions>
- <action type="Redirect" url="http://www.{C:0}/{R:0}"
- redirectType="Permanent" />
- </rule>
- </rules>
- </rewrite>
To convert a www to a non-www:
- <rewrite>
- <rules>
- <rule name="Canonical" stopProcessing="true">
- <match url=".*" />
- <conditions>
- <add input="{HTTP_HOST}" pattern="^www[.](.+)" />
- </conditions>
- <action type="Redirect" url="http://{C:1}/{R:0}"
- redirectType="Permanent" />
- </rule>
- </rules>
- </rewrite>