Redirecting Non-www to Domain Equivalent
A question came up on a blog post of mine on how to redirect a domain name that doesn’t have www in it while retaining the original domain name. Basically, to have a generic redirect to add on a www if it’s not already there.
For example, how could you have something.com always redirect to www.something.com where something could be any of a number of domain names that you manage.
This is fully possible with URL Rewrite. Here’s what the config looks like. If you want a full walkthrough using the setup wizard then refer to my previous post for the details.
<rule name="non-www to www" enabled="true" stopProcessing="true">
<match url=".*" />
<conditions>
<add input="{HTTP_HOST}" pattern="^[^\.]+\.[^\.]+$" />
</conditions>
<action type="Redirect" url="http://www.{HTTP_HOST}/{R:0}" />
</rule>
This rule watches for all 2 level domains and redirects to the same domain name and tacks on the www to the beginning. So something.domain.com won’t be redirected, but domain.com will.
Alternately, if visitors will come in through either http or https, you can ensure that this retains the protocol with 2 rules, one for each:
<rule name="non-www to www http" enabled="true" stopProcessing="true">
<match url=".*" />
<conditions>
<add input="{HTTP_HOST}" pattern="^[^\.]+\.[^\.]+$" />
<add input="{HTTPS}" pattern="off" />
</conditions>
<action type="Redirect" url="http://www.{HTTP_HOST}/{R:0}" />
</rule>
<rule name="non-www to www https" enabled="true" stopProcessing="true">
<match url=".*" />
<conditions>
<add input="{HTTP_HOST}" pattern="^[^\.]+\.[^\.]+$" />
<add input="{HTTPS}" pattern="on" />
</conditions>
<action type="Redirect" url="https://www.{HTTP_HOST}/{R:0}" />
</rule>