bdcoder
bdcoder

Reputation: 3809

IIS rewrite rule for http to https with canonical host

Environment:

Challenge

Completely new to rewrite rules and I need to implement a rule that does two things:

  1. Change protocol from http to https
  2. Change host name to www.example.com

Problem is I cannot really test this per se, because our SSL certificate only exists on our production site, so I need to make sure I get this right.

In doing the research I found the documentation regarding rewrite rules somewhat sparse, but cobbled together the following from various examples, etc.:

    <rule name=”http_to_https_redirect">
     <match url="(.*)" />
<conditions><add input="{HTTPS}" pattern="^OFF$" ignoreCase="true" />
</conditions>
     <action type="Redirect" url="https://www.example.com/{R:1}" redirectType="Permanent" />
    </rule>

I still have no clue as to what {R:1} means or how it behaves as I found only a short blurb about it being a “Back-references to rule patterns are identified by {R:N} where N is from 0 to 9. Note that for both types of back-references, {R:0} and {C:0}, will contain the matched string.” (from: https://www.iis.net/learn/extensions/url-rewrite-module/url-rewrite-module-configuration-reference)

Question:

Is the above rule correct as per points 1 and 2 above?

Hopefully someone with a little more experience can confirm – yes / no ?

Also found this post: IIS Url Rewrite rule HTTP to HTTPS AND add WWW ... but the actual rewrite rule was never posted in the answer!

Upvotes: 1

Views: 1763

Answers (1)

bdcoder
bdcoder

Reputation: 3809

The rewrite url to accomplish the redirect using https and the canonical host is as follows:

  <rewrite>
   <rules>
    <rule name="redirect_http_to_https_with_canonical_host" stopProcessing="true">
     <match url="(.*)" />
     <conditions logicalGrouping="MatchAny" trackAllCaptures="false">
       <add input="{HTTPS}" pattern="off" />
       <add input="{HTTP_HOST}" pattern="www\.example\.com" negate="true" /> 
     </conditions>
     <action type="Redirect" url="https://www.example.com{URL}" appendQueryString="true" redirectType="Permanent" />
    </rule>
   </rules>
  </rewrite>

The above works for the following cases:

Input:  http://example.com
Result: https://www.example.com

Input:  http://www.example.com
Result: https://www.example.com

Input:  http://example.com/somepage.aspx   
Result: https://www.example.com/somepage.aspx

Input:  http://example.com/somepage.aspx?q=test
Result: https://www.example.com/somepage.aspx?q=test

Input:  https://example.com
Result: https://www.example.com

Input:  https://www.example.com
Result: https://www.example.com

Input:  https://example.com/somepage.aspx   
Result: https://www.example.com/somepage.aspx

Input:  https://example.com/somepage.aspx?q=test
Result: https://www.example.com/somepage.aspx?q=test

Upvotes: 2

Related Questions