How to create subdomains for IIS7 programmatically

2020-05-27 13:27发布

问题:

I'm writing a SaaS app in C#/ASP.NET, hosted with IIS7. I want to create a personalized subdomain for every customer that signs up, i.e. fred.mydomain.com, bob.mydomain.com, each of which will point to the same app, just with a different skin per customer.

How do I create these subdomains programmatically?

回答1:

Use URL Rewrite for IIS7 to map all requests like user.mydomain.com (where user is not www, mail or other existing real subdomains) to mydomain.com/myapp?id=user Then in the script handle whatever theming you need.

You do not need to add rule for every user created. Just create one general rule to do so.

And, also, in your server DNS, you need to forward *.mydomain.com (where * is not www, mail or other existing real subdomains) to mydomain.com IP. This is pretty straight forward. You already have DNS records for existing subdomains. Just add *.mydomain.com and point to mydomain.com. This will do the DNS part of the trick. Other part is in the URL Rewrite



回答2:

Realizing of course that someone already answered your question by telling you to do redirects, it seems the easier way might be to just grab the host server variable.

  1. Setup IIS so that all incoming requests (regardless of the host header) point to this one application. All sites have to either have a unique hostname or unique port in IIS, so you would set this up by:

    1. Binding the site to the default port of 80.

    2. Not providing anything in the Host Name field. This is also how the Default Website is setup by default when you first install IIS.

  2. Figure out the static IP address of your server, and tell each new client that signs up to point the DNS for their domain to that IP. Or, if you will own the domain name, setup a catchall DNS entry: *.mydomain.com - points to the IP address of your server.

  3. Within your application, check for the current host header in order to provide a different skin or master page.

This should grab the host header from within the code:

  Request.ServerVariables["HTTP_HOST"]

From there you could test its value against a set of database values you have to determine which MasterPage/css stylesheet/etc you need to load based on that URL. Keep in mind if you do a catchall like this that you'll need to account for a URL mistyped that you therefore wouldn't have a skin to match to it.