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?

  • we need to know what version of iis you are using – Michael Henderson Feb 1 '18 at 17:15
  • @MichaelHenderson I actually have two servers one is IIS 7.5 the other is IIS 10.0 – userSteve Feb 1 '18 at 19:14

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

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:

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

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.

|improve this answer|||||
  • 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). <rule name="Strip www from URL and retry" enabled="true" patternSyntax="ECMAScript" stopProcessing="true"> <match url="(.*)" negate="false" /> <conditions logicalGrouping="MatchAny"> <add input="{HTTP_HOST}" pattern="^(www\.)(.*)$" /> </conditions> <action type="Redirect" url="http://{C:2}{PATH_INFO}" redirectType="Permanent" /> </rule> – userSteve Feb 5 '18 at 17:32
  • 1
    Whoops! cut and paste error from my previous post. Thanks for the correction. – sippybear Feb 5 '18 at 21:12

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.