2
votes

My goal is to have rule(s) in IIS/Azure's web.config file to successfully redirect the following client request examples:

HTTPS redirect:

No-www & HTTPS redirect:

No-www, HTTPS redirect & maintain path:

Here's what I have so far, which only is achieving point 1 and 2. If a visitor lands directly on a subpage, they aren't redirected to non-www and aren't redirected to HTTPS.

    <rule name="Redirect to https">
      <match url="(.*)"/>
      <conditions>
        <add input="{HTTPS}" pattern="Off"/>
        <add input="{REQUEST_METHOD}" pattern="^get$|^head$" />
      </conditions>
      <action type="Redirect" url="https://{HTTP_HOST}/{R:1}"/>
    </rule>
    <rule name="Canonical Hostname" stopProcessing="false">
      <match url="(.*)" />
      <conditions logicalGrouping="MatchAll" trackAllCaptures="false">
        <add input="{HTTP_HOST}" pattern="^(www\.)(.*)$" />
      </conditions>
      <action type="Redirect" url="https://{C:2}{REQUEST_URI}" redirectType="Permanent" />
    </rule>

I've exhausted multiple search result pages and multiple StackOverflow questions without any luck - they all promise to be able to achieve the third point (redirect to a non-www, HTTPS page and maintain the path) but they haven't worked for me.

Thanks for taking the time to read this!

1

1 Answers

2
votes

I discovered the problem, which is partly due to the way I presented my question (sorry, StackOverflowers!).

The issue was the ordering of the rules. I've put the following (new) rules at the top of my rules section, in the following order, for those who suffer this problem in the future. Now, it is redirecting to HTTPS, with no-www, and maintaining the path that was requested by the client.

  <rule name="Canonical Hostname" stopProcessing="false">
    <match url="(.*)" />
    <conditions logicalGrouping="MatchAll" trackAllCaptures="false">
      <add input="{HTTP_HOST}" pattern="^(www\.)(.*)$" />
    </conditions>
    <action type="Redirect" url="http://{C:2}{REQUEST_URI}" redirectType="Permanent" />
  </rule>
  <rule name="Force HTTPS" enabled="true">
    <match url="(.*)" ignoreCase="false" />
    <conditions>
      <add input="{HTTPS}" pattern="off" />
    </conditions>
    <action type="Redirect" url="https://{HTTP_HOST}/{R:1}" appendQueryString="true" redirectType="Permanent" />
  </rule>