Redirecting all URLs to their HTTPS WWW equivalents
Whether you’re a no-www or a yes-www person (you can guess which one I am based on the URL currently present on your address bar 🙂), one thing is certain – you need to be consistent. This means that if you like www, then yourdomain.com should redirect (301 permanent) to www.yourdomain.com, and if you don’t like it then the redirection needs to go the other way around. Either way, you can’t have people browsing the same page from different domain (with www and without it), it’s just confusing.
In addition, you really should be using SSL everywhere, all the time. Certificates are free, and even if your hosting plan doesn’t support them (as is the case with Azure’s free tier), you can have CloudFlare take care of that for you (and enjoy improved performance and security as a bonus). Once you have SSL up and running, you’d want to redirect all HTTP traffic to HTTPS and enable HSTS for increased security.
To recap – once you’ve decided whether you like www or not, and finished setting up SSL, you want your redirections to look like this (assuming yes-www):
- HTTP://yourdomain.com -> HTTPS://www.yourdomain.com
- HTTP://www.yourdomain.com -> HTTPS://www.yourdomain.com
- HTTPS://yourdomain.com -> HTTPS://www.yourdomain.com
In addition, you want HSTS headers (Strict_Transport_Security) in place. Fortunately, using the IIS Rewrite module (installed by default on Azure deployments), accomplishing all of the above is a breeze:
<system.webServer>
<rewrite>
<rules>
<rule name="Redirect to www" stopProcessing="true">
<match url="(.*)" />
<conditions logicalGrouping="MatchAny">
<add input="{HTTP_HOST}" pattern="^yourdomain\.com"/>
<add input="{HTTPS}" pattern="off" ignoreCase="true"/>
</conditions>
<action type="Redirect"
url="https://www.yourdomain.com/{R:1}"
redirectType="Permanent"/>
</rule>
</rules>
<outboundRules>
<rule name="HSTS" enabled="true">
<match
serverVariable="RESPONSE_Strict_Transport_Security"
pattern=".*" />
<conditions>
<add input="{HTTPS}" pattern="on" ignoreCase="true" />
</conditions>
<action type="Rewrite" value="max-age=31536000" />
</rule>
</outboundRules>
</rewrite>
</system.webServer>
</configuration>
Happy rewriting 😉
Leave a Comment