Common redirects with IIS

Monday, 17 May 2021

The two most common redirects I generally have to implement are

  1. HTTP to HTTPS
  2. apex (or naked/root) to www - i.e., brendanmckenzie.com to www.brendanmckenzie.com

HTTP to HTTPS

The easiest way to handle this is with the built-in functionality.

1<rule name="HTTPS redirect" enabled="true" stopProcessing="true">
2  <match url="*" />
3  <conditions logicalGrouping="MatchAny">
4    <add input="{HTTPS}" pattern="OFF" />
5  </conditions>
6  <action type="Redirect" url="https://{HTTP_HOST}{REQUEST_URI}" redirectType="Permanent" />
7</rule>

Things get tricky when IIS isn't the server handling the inbound requests, such as in load-balanced environments. Ideally, the load balancer will handle the redirect, but sometimes it's not an option.

In that case (hopefully) the load balancer will forward something letting you know the protocol used (HTTP or HTTPS).

1<rule name="HTTPS redirect" enabled="true" stopProcessing="true">
2  <match url="*" />
3  <conditions logicalGrouping="MatchAny">
4    <add input="{HTTP_X_FORWARDED_PROTO}" pattern="http" />
5  </conditions>
6  <action type="Redirect" url="https://{HTTP_HOST}{REQUEST_URI}" redirectType="Permanent" />
7</rule>

apex to www.

Aligning with this. A common request is to have "naked" or "apex" domains forwarded to www, such as brendanmckenzie.com to www.brendanmckenzie.com.

This can be simply handled with the following rule.

1<rule name="apex to www" enabled="true" stopProcessing="true">
2  <match url="(.*)" ignoreCase="false" />
3  <conditions logicalGrouping="MatchAll">
4    <add input="{HTTP_HOST}" pattern="^brendanmckenzie.com$" negate="false" />
5  </conditions>
6  <action type="Redirect" url="https://www.brendanmckenzie.com/{R:1}" />
7</rule>