3

I need to find an easy and universal way of catching any http://www.sub.example.com URLs and redirecting them to http://sub.example.com (ie stripping out the www)

I'd prefer to implement this once for the server and not for each site, maybe using IIS Rewriter?

Joel Coel
  • 12,932
  • 14
  • 62
  • 100
userSteve
  • 1,573
  • 4
  • 23
  • 33

1 Answers1

2

You'll want to make a redirect rule in IIS URL Rewrite Module as follows:

Match URL
Requested URL: Matches the Pattern
Using: Regex
Pattern: * and Ignore case

Conditions
Logical grouping: Match Any
Input: {HTTP_HOST}
Type: Matches the Pattern Pattern: ^(www\.)(.*)$

Server Variables Leave blank.

Action Action type: Redirect
Redirect URL: https://{C:2}{PATH_INFO}
Append query string: checked Redirect type: Permanent (301)

Apply the rule and run IISReset.

Alternatively, after installing the module you could modify web.config as follows:

<rewrite>
    <rules>
        <rule name="Strip www" enabled="true" patternSyntax="Regex" stopProcessing="true">
            <match url="*" negate="false" />
            <conditions logicalGrouping="MatchAny">
                <add input=""{HTTP_HOST}" pattern="^(www\.)(.*)$" />
            </conditions>
            <action type="Redirect" url="https://{C:2}{PATH_INFO}" redirectType="Permanent" />
        </rule>
    </rules>
</rewrite>

This rule is meant to check any URL (*), find an instance of "www." (case insensitive by default) in {HTTP_HOST}, and then redirect to the second part of the canonical hostname {C:2} with the rest of path appended to the end {PATH_INFO}. This rule may fail you if there was a request for something like http://bad.www.example.com/some/page.html as it would return https://www.example.com/some/page.html, but it should work for most cases.

sippybear
  • 3,197
  • 1
  • 13
  • 12
  • Thanks ! Needed a couple of tweaks to get it work, but it now works great. (You specified "Wildcard" but then went on to use a Regex). – userSteve Feb 05 '18 at 17:32
  • 1
    Whoops! cut and paste error from my previous post. Thanks for the correction. – sippybear Feb 05 '18 at 21:12