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?
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:
*
andIgnore 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:
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 returnhttps://www.example.com/some/page.html
, but it should work for most cases.