Redirecting multiple domains to one (especially non-www to www) is the most common requirement we receive as a sysadmin, and there are plenty of examples online showing how to do this using the IIS URL Rewrite Module.
But, most of them use separate rules for redirecting each domain resulting in a messed up web.config file. The problem is bcoz of using multiple rules for each redirection which can be fulfilled with a single rule.
The example I will describe is for an F&B project I worked for the UK client. The requirement is to redirect multiple domains into a single domain. I will describe in detail later.
The client is starting a food delivery site with www.mydomain.com and he wants all the www and non-www of mydomain.net|online|uk|info| to be redirected to www.mydomain.com. Also, he wants www and non-www of mydomain2.com redirected to www.mydomain.com.
Requirement
Main domain: www.domain.com
Redirect:
mydomain.com -> www.mydomain.com
www.mydomain.net -> www.mydomain.com
mydomain.net –> www.mydomain.com
www.mydomain.online -> www.mydomain.com
mydomain.online –> www.mydomain.com
www.mydomain.uk -> www.mydomain.com
mydomain.uk –> www.mydomain.com
www.mydomain.info -> www.mydomain.com
mydomain.info –> www.mydomain.com
www.mydomain2.com -> www.mydomain.com
mydomain2.com –> www.mydomain.com
In order to achive this, we can take advantage of the URL Rewrite Module, a handy IIS component which is downloadable for free from this page or by using the Microsoft Web Platform. Once installed, you can check its presence by opening the IIS Admin Interface and looking for a new icon called URL Rewrite.
Now you can choose between using it by learning the GUI commands or manually set its rules in your website’s web.config file. In this post, we’ll go for the web.config XML syntax, which is robust, solid and also well documented by Microsoft here.
Create, if it doesn’t exist already, a <system.webServer> section and copy & paste the following code. Be sure to replace mydomain with the hostname of your website and the net|online|uk|info| with the only root domains you require and mydomain2 with the other domain names you want to 301 redirect to it.
<system.webServer><rewrite><rules><rule name=“Non-canonical hostnames to www.mydomain.com” patternSyntax=“ECMAScript” stopProcessing=“true”><match url=“.*” /><conditions logicalGrouping=“MatchAny”><add input=“{HTTP_HOST}” pattern=“^mydomain.com$” /><add input=“{HTTP_HOST}” pattern=“^(www.)?mydomain.(net|online|uk|info)$” /><add input=“{HTTP_HOST}” pattern=“^(www.)?mydomain2.com$” /></conditions><action type=“Redirect” url=“http://www.mydomain.com/{R:0}” /></rule></rules></rewrite></system.webServer>