Skip to main content

IIS URL rewrite – force non-WWW and SSL

Almost every client I work for I have to force some redirecting on the IIS for either security or SEO reasons, and I always forgot how to do it. So to help myself I’ll post it here so I can focus on more fun stuff. Remember that you need to install the URL rewrite extension on the IIS before it will work. Otherwise you will get an invalid web.config error.

Force SSL – HTTP to HTTPS

<rule name="Force SSL" stopProcessing="true">
 <match url="(.*)" />
 <conditions>
 <add input="{HTTPS}" pattern="off" />
 </conditions>
 <action type="Redirect" url="https://{HTTP_HOST}/{R:1}" />
 </rule>

Force non-WWW & SSL – HTTP to non www HTTPS

<rule name="Force non-WWW HTTPS" enabled="true" stopProcessing="true">
 <match url="(.*)" />
 <conditions logicalGrouping="MatchAny">
 <add input="{HTTP_HOST}" pattern="^(www\.)(.*)$" />
 <add input="{HTTPS}" pattern="off" />
 </conditions>
 <action type="Redirect" url="https://{HTTP_HOST}/{R:1}" appendQueryString="true" />
 </rule>

Redirect everything under “/path” to root

<rule name="Redirect /path and subpages" stopProcessing="true">
 <match url=".*" />
 <conditions logicalGrouping="MatchAny">
 <add input="{REQUEST_URI}" pattern="path/(.*)" />
 <add input="{REQUEST_URI}" pattern="^/path()$" />
 </conditions>
 <action type="Redirect" url="https://{HTTP_HOST}/{C:1}" />
 </rule>

For example you have a blog, “dinbror.dk/blog” and now you want the blog to live at your root domain instead of under “/blog”, so the above redirect with redirect “dinbror.dk/blog/iis-url-rewrite-force-non-www-and-ssl/” to “dinbror.dk/iis-url-rewrite-force-non-www-and-ssl/”.

Redirect subdomain to domain

<rule name="Subdomain Redirect" stopProcessing="true">
 <match url=".*" />
 <conditions>
 <add input="{HTTP_HOST}" pattern="^(www\.)?blog\.dinbror\.dk$" />
 </conditions>
 <action type="Redirect" url="http://dinbror.dk/blog" />
 </rule>

Above rule will redirect “www.blog.dinbror.dk” and “blog.dinbror.dk” to “dinbror.dk/blog”.
If you want to redirect to the same domain as the subdomain has you can make it dynamic with the following rule:

<rule name="Subdomain Redirect - Pharma" stopProcessing="true">
 <match url=".*" />
 <conditions>
 <add input="{HTTP_HOST}" pattern="^(www\.)?blog\.(dinbror\.dk)$" />
 </conditions>
 <action type="Redirect" url="https://{C:2}/blog" />
 </rule>

Leave a Reply

Your email address will not be published. Required fields are marked *