Tuesday, September 23, 2008

ASP.NET and subdomains - reloaded

This one is in response to Mauricio's comment on my old post about handling subdomains in ASP.NET. I'll try to be as brief as possible this time.

Ok, so our task is writing an application where every user has his/her own homepage located under a subdomain of the root domain. For an example my homepage at http://coolapp.com would be located at http://maciek.coolapp.com.

First things first: DNS. I'm no expert in DNS configuration but I know that what's needed is a wildcard A record pointing to the IP of the server hosting the application.

At this point we'll have all request to *.coolapp.com directed to our server.

Next, we need an application to handle the requests. One application can handle request for all users. When handling the request we can use HttpContext.Current.Request.Host to figure out which user homepage to render. Host property will return for example "maciek.coolapp.com", so we can get a username as simply as Host.Split('.')[0].

We're almost there. Now we need to make sure the cookies we send to the browser are valid in all subdomains, otherwise we'll end up creating a separate cookie for every subdomain. For details see my old post: http://mgrzyb.blogspot.com/2007/12/aspnet-and-subdomains.html.

I could end it here but if you're working on anything serious you will probably want to use SSL for at least login form. If the login form can be accessed from a subdomain not just the root domain you will need to get yourself a "wildcard" SLL certificate that covers all the subdomains - we got one from DigiCert.

Congratulations - you're done!