IIS – How to Redirect www.* URLs

iisrewrite

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?

Best Answer

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.