This post addresses the situation in which you want to redirect all subdomains to your main domain and you are using host headers in IIS. The main problem is the host header binding in IIS does not allow wildcards. Since you can not use wildcard host headers any subdomain requests will never reach your web site’s URL Rewrite processing. The following is the technique I use to do subdomain redirects on a web server hosting multiple sites using host headers.
For example lets say you have a web server that hosts www.abc-test1.com and xyz-test2.com. You want all subdomain requests to return 301 redirects to the main domain.
First you’ll need to configure your DNS host to map all subdomains to your web site IP address. For www.abc-test1.com this will be something like *.abc.com. How you accomplish the DNS configuration will depend on who handles your DNS. If your DNS provider does not provide wildcard DNS entries you’ll want to find one who does.
Create a web site without a host header defined. This web site will use URL Rewrite to redirect subdomain requests to your main domain. I chose to call this web site Redirector. It should never respond to web requests, so it is essentially an empty web site. The binding for the redirector site will look like the following:
Your host header bindings for www.abc-test1.com and xyz-test2.com:
Your rewrite rules in the web.config file on the redirector site will look something like the following:
<? xml version = "1.0" encoding = "UTF-8" ?> < configuration > < system.webServer > < rewrite > < rules > < rule name = "abc-test1 Redirect" stopProcessing = "true" > < match url = "(.*)" /> < conditions > < add input = "{HTTP_HOST}" pattern = ".*abc-test1\.com" /> < add input = "{HTTP_HOST}" negate = "true" pattern = "www\.abc-test1\.com" /> </ conditions > < action type = "Redirect" url = "http://www.abc-test1.com/{R:1}" redirectType = "Permanent" /> </ rule > < rule name = "xyz-test2 Redirect" stopProcessing = "true" > < match url = "(.*)" /> < conditions > < add input = "{HTTP_HOST}" pattern = ".*xyz-test2\.com" /> < add input = "{HTTP_HOST}" negate = "true" pattern = "^xyz-test2\.com$" /> </ conditions > < action type = "Redirect" url = "http://xyz-test2.com/{R:1}" redirectType = "Permanent" /> </ rule > </ rules > </ rewrite > </ system.webServer > </ configuration > |
The above rewrite rules will look the following in the GUI configuration:
Given the above configuration if you request any subdomains they will be permanently redirected to the main domain. For example: test.abc-test1.com, www2.abc-test1.com, abc-test2.com, and any variation will be 301 redirected to www.abc-test1.com. Likewise test.xyz-test2.com, www2.xyz-test.com, www.xyz-test2.com, and any variation will be 301 redirected to xyz-test2.com.
There are likely other ways to accomplish subdomain redirects, but this is working out for me. Hopefully this helps someone else as well.
No comments:
Post a Comment