Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Web.config URL Rewrites - HTTPS and Non-WWW

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:

  • http://www.iis.net/learn/extensions/url-rewrite-module/url-rewrite-module-configuration-reference
  • http://madskristensen.net/post/url-rewrite-and-the-www-subdomain
  • how to set asp.net web.config rewrite http to https and www to non-www

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:

  • testing.com ---> https://testing.com
  • www.testing.com ---> https://testing.com
  • www.testing.com/xyz/ ---> https://testing.com/xyz/
like image 538
Rob Scott Avatar asked Oct 30 '22 20:10

Rob Scott


1 Answers

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>
like image 130
Rob Scott Avatar answered Nov 10 '22 16:11

Rob Scott