5
votes

I need to have both https and non-www rewrites, while also NOT HARDCODING the domain, since we have numerous servers. This needs to be in the web.config, not in IIS.

I've read numerous articles:

The https rewrite works, the non-www does not.

    <rule name="Redirect to HTTPS" stopProcessing="true">
      <match url="(.*)" />
      <conditions>
        <add input="{HTTPS}" pattern="^OFF$" />
      </conditions>
      <action type="Redirect" url="https://{HTTP_HOST}/{R:1}" redirectType="Permanent" />
    </rule>
    <rule name="Remove WWW" patternSyntax="Wildcard" stopProcessing="true">
      <match url="*" />
      <conditions>
        <!--<add input="{CACHE_URL}" pattern="*://www.*" />-->
        <!--<add input="{HTTP_HOST}" pattern="*://www.*" />-->
        <add input="{HTTP_HOST}" pattern="^.*www.*" />
      </conditions>
      <action type="Redirect" url="https://{SERVER_NAME}/{R:1}" redirectType="Permanent" />
      // i've also tried
      // url="{C:2}/{R:1}"
      // url="{C:1}/{C:2}"
    </rule>

I tested the regex for ^.*www.* on a regex tester and it was matching www.testing.com but not testing.com - so I would assume the pattern would catch it.

I need the URLs to redirect from:

2

2 Answers

2
votes

Was my own issue - there was no DNS for the www, therefore the redirect wouldn't resolve on it's own.

Code used:

    <rule name="Redirect to HTTPS" stopProcessing="true">
      <match url="(.*)"/>
      <conditions>
        <add input="{HTTPS}" pattern="^OFF$"/>
      </conditions>
      <action type="Redirect" url="https://{HTTP_HOST}/{R:1}" redirectType="Permanent"/>
    </rule>
    <rule name="Remove WWW" patternSyntax="Wildcard" stopProcessing="true">
      <match url="*" />
      <conditions>
        <add input="{CACHE_URL}" pattern="*://www.*" />
      </conditions>
      <action type="Redirect" url="{C:1}://{C:2}" redirectType="Permanent" />
    </rule>
0
votes

Add a "Canonical domain name" rule. IIS 10

The soulution Rob found works fine as well. Mine seems to be a bit easier IMHO.