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!


Anonymous said...

Hi Maciej !!!
Thanks for your help! Your answer was very helpful for me. So, I'd like to ask you some other little things (sorry, i am abusing your generosity :D).
The first one is related with the way you manage each request from different subdomains. I understand how DNS wildcards works. So, I understand you must parse the url from request, and then check, for example, if the subdomain-user you get is already registered in the database of the application. If so, you can figure out which page to render, right?
Well, the idea is the user can reach all its stuff through userxx.myapp.com/profile instead myapp.com/users/profile.aspx?userid=8. Does it make sense for you? The goal is keeping a clean url. How do you manage this issue?
Do you dynamically create each subdomain in your hosting server?
Or do you use url rewriting for this? Do you have any code sample code for testing that?
Sorry for my annoying questions :(.
I hope you can help me with this.
Many, many thanks in advance!

Rem said...

Nice post...

nintendo ds r4 said...

Nice post. Thanx for sharing this valuable information. Please provide more information over it. Provide links to related topics if possible.