How to set up URL Rewrite on IIS7 so that multiple subdomains redirect to the correct web site

asp.netiis-7url-rewriting

I asked a previous question about how to have multiple subdomains all pointing at the same site; the answer I accepted there was to use URL Rewrite.

Cool. But for the life of me I cannot figure out how URL Rewrite works, and I consider myself a relatively smart guy. |-) Lots of questions…

  • Each customer (and there will be hundreds, if not thousands) gets their own subdomain e.g. customer1.mydomain.com, cooldude.mydomain.com etc. The regex would be (.+)\.mydomain\.com, and all of these URLs should be redirected to a website on IIS that I've named customers.mydomain.com. All the examples I've found on URL Rewrite are about referencing documents, e.g. mydomain.com/thing.aspx?id=123 changes to mydomain.com/thing/123, which I'm not really interested in. Here's a clue: as you can see in the picture below, the "Input" column always says "URL path after '/'" – but there doesn't appear to be any way to change that.

URL Rewrite pic

  • I am assuming that the rewrite rule should be put on the default web site, but I want the rule to redirect to the customers.mydomain.com web site. How do you force the redirect to a specific web site, in such a way that I will still be able to see the subdomain name (which determines the customer site I'm logging into)?

Best Answer

I think what you want to do to get this to work is add an input condition to your rewrite rule. You can read about it in the "Referencing a rewrite map from rewrite rule" section at http://learn.iis.net/page.aspx/469/using-rewrite-maps-in-url-rewrite-module/.

Here's an example I think will work for you:

<rule name="My Rule">
    <match url="(.+)?" negate="false" />
    <action type="Redirect" url="http://{C:1}.mydomain.com/{R:0}" />
    <conditions>
    <add input="{HTTP_HOST}" pattern="(.+)\.mydomain\.com" />
    </conditions>
</rule>
Related Topic