IIS URL Rewrite – Redirect multiple domain names to one

Consider this a 2nd part to IIS URL Rewrite – rewriting non-www to www.  Reader Rubens asked about redirecting multiple domain names in a single rule.  That’s a good question and worth writing a part II blog post about it.

Here’s his question:

If there any generic way to do that if we have multiple domains with
multiple extensions?example:
mydomain.com to www.mydomain.com (already done)
mydomain.net to www.mydomain.com
www.mydomain.net to www.mydomain.com
etccc...
and maybe also
www.mydomain2.net to www.mydomain.com
etccc...
Thanks.


Regular expressions are great for handling .com / .net / .org in a single condition.  You can do this using a “Condition input” check for {HTTP_HOST} with a “Pattern” of:
^domain.(com|net|org)$

Note that the ^ marks the beginning of the pattern and the $ marks the end when using regular expressions. 
 
Additionally, to handle the mydomain2.net, be sure to set the “Logical Grouping” to Match Any.  This allows any of the rules to cause the rule to match the condition and redirect.  After setting to Match Any, you can add as many domains as you want with a single rule with multiple conditions.
 
Let’s look at mydomain2.com and .net.  Here’s a Pattern that will catch all situations:
^(www.)?mydomain2.(com|net)$

This catches www and non-www and .com and .net.
 
The following screenshot shows conditions that will catch the following:
  • domain.com (1st condition)
  • domain.net (1st condition)
  • www.mydomain2.com (2nd condition)
  • www.mydomain2.net (2nd condition)
  • mydomain2.com (2nd condition)
  • mydomain2.com (2nd condition)
  • www.domain.net (3rd condition)
image
 
Note that the Action will redirect all of them to the same place (www.domain.com), which was Rubens’ goal.  Just be sure that no conditions match www.domain.com or you’ll create a loop.
 
The config that results should look like this:
 
<rewrite>
    <globalRules>
        <rule name="Redirects to www.domain.com" patternSyntax="ECMAScript" stopProcessing="true">
            <match url=".*" />
            <conditions logicalGrouping="MatchAny">
                <add input="{HTTP_HOST}" pattern="^domain.*(com|net)$" />
                <add input="{HTTP_HOST}" pattern="^(www.)?mydomain2.(com|net)$" />
                <add input="{HTTP_HOST}" pattern="^www.domain.net$" />
            </conditions>
            <action type="Redirect" url="http://www.domain.com/{R:0}" />
        </rule>
    </globalRules>
</rewrite>
 
You can do this using wildcards too.  It would take more conditions.  It’s also possible to do this with rewrite maps, another feature of URL Rewrite.

No Comments