CodeBetter.Com
CodeBetter.Com
RSS 2.0 via Feedburner
           Do you Twitter? Follow us @CodeBetter

Brendan Tompkins [MVP]

Blog First. Ask Questions Later.

Create Unlimited Subdomains with HTTP Modules

I recently took the hundred or so top search words for CodeBetter.Com and created an “Explore CodeBetter” control with links to pages about those search words.  I wanted the links to be to a subdomain with the keyword as the first label of the subdomain.  So, agile would link to agile.codebetter.com, which internally would be forwarded to a handler that hooks into Community Server’s search engine and presents a list of pages containing the word agile.  As implemented, this control currently looks like this:

Setting up DNS

If your DNS supports wildcard syntax, you’ll be able to do this.   Basically you just want to forward all requests to *.yourdomain.com to yourdomain.com.  If your ISP’s dns doesn’t support the wildcard syntax, you could handle your own DNS on your server.

Setting up IIS

If you use host headers and you’ve got a bunch of different sites configured, you’ll need to add a blank host header, so that any requests for subdomains not listed  get forwarded to the proper website.   If you want to set this up for multiple websites per server, I’m not sure how to do this, perhaps someone out there knows how.  Basically the hostheader configuration won’t accept *.yourdomain.com, so I’m not sure how to set this up, except to have all un-configured domains going to one website using the blank hostheader technique.

Creating the HTTP Module

Next, you’ll need to intercept the request, inspect the requested URL and forward requests appropriately.  A good way to do this is by creating an IHttpModule and plugging it into the pipeline.  For forwarding, all you’ll need to do is handle the OnBeginRequest event, and then use Server.Transfer to forward the request.  The nice side-effect of this is that the URL in the browser doesn’t change when using Server.Transfer (as opposed to Response.Redirect), leaving your nice clean URL in the browser.  Here’s the code for my handler.  I also do some checking to make sure that the homepage (default.aspx) was requested, because I don’t want to do this on sub-page requests. 

   public class SubdomainModule : IHttpModule

    {

        public void Init(HttpApplication app)

        {

            // register for pipeline events

            app.BeginRequest += new EventHandler(this.OnBeginRequest);

        }

 

        public void Dispose() {}

 

        public void OnBeginRequest(object o, EventArgs args)

        {

 

            // get access to app and context

            HttpApplication app = (HttpApplication)o;

            HttpContext ctx = app.Context;

 

            if (!(app.Context.Request.Url.Host.StartsWith("codebetter") || app.Context.Request.Url.Host.StartsWith("www")))

            {

                if (ctx.Request.Path.ToUpper() == "/DEFAULT.ASPX")

                {

                    string[] domainParts = app.Context.Request.Url.Host.Split(".".ToCharArray());

                    if (domainParts.Length > 2)

                        ctx.Server.Transfer("/explore/explore.aspx?q=" + domainParts[0]);

                }

            }

        }

    }

Registering the Module in the pipeline

This is simple, you can just add the following to your web.config file:

<httpModules>
   <add name="SubdomainModule" type="Tompkins.Cs.Subdomains.SubdomainModule, Tompkins.Cs.SubdomainHandler" />
</httpModules>

That’s it!  Any requests will be forwarded.  You can now simply request any subdomain on codebetter, like http://monkeys.codebetter.com or http://baseball.codebetter.com.  Need advice on relationships or read that funny post about my ex-girlfriend finding my blog?  Just type http://girlfriend.codebetter.com.  Heck, you could even use us as a help system!  If you need to know about ADO, just type http://ado.codebetter.com. Good luck!

-Brendan 

 



Comments

Steve said:

You can't imagine how many times I've wondered what the best way to find all the posts about monkeys was on the codebetter.com site! :)
# June 27, 2006 12:32 PM

Brendan Tompkins said:

Steve,  yes, I've often wondered the same...  :) I'm actually quite suprised at the number of monkey posts!
# June 27, 2006 1:20 PM

Community Server Daily News said:

Community Server featured in a Forrester Wave™ Vendor Summary with the title, &quot;Telligent Provides A Strong,
# June 27, 2006 2:47 PM

dotnetkicks.com said:

Trackback from dotnetkicks.com
# June 27, 2006 4:33 PM

Jason Haley said:

# June 27, 2006 5:11 PM

Tiernans Comms Closet said:

Now, this is an interesting idea: create unlimited sub domains using HTTP modules on .NET. This could...
# June 28, 2006 7:44 AM

Jeffrey Palermo said:

# June 28, 2006 10:38 AM

Vince said:

Just wondering...
why did you choose to compare strings using:
(ctx.Request.Path.ToUpper() == "/DEFAULT.ASPX")

Would a case-insensitive compiled Regex.IsMatch() be faster/better?
# June 28, 2006 1:43 PM

Brendan Tompkins said:

Vince,

I think you're right.. I've actually gone back into this code to refactor for stuff like this.. (Theres some embarrasing mix of local variable ctx versus using the context instance stuff going on too)...  

I'm usually not a big perf guy, but with this code, since it's running on every request, I'd error on the side of performance,  which is a round about way of saying you're right, but I usually use string comparisons for readability.

Thanks!  
# June 28, 2006 1:56 PM

Soheilkh said:

Hi
is maybe that map the subdomain in localhost.
i can't test your sample code .when i request subdomain in addressbar SubdomainModule can't hanlde request.
how i do?
plz help me
# June 29, 2006 10:49 AM

Brendan Tompkins said:

Soheikh, have you setup your wildcard DNS to point to your website?  
# June 29, 2006 10:54 AM

Aaron Erickson said:

Great stuff!  Of course, this is a great demo of what, in general, you can do with HttpModules.  I already wrote my own module that allows me to map a database that has landing URLs (for consumption by google) - to the appropriate querystringed URL via a 301 redirect - using your module as inspiration... brilliant!
# June 29, 2006 11:55 AM

soheilkh said:

i can't access to dns setup .
is way that map all subdomain in iis setup
# June 30, 2006 6:48 AM

Brendan Tompkins said:

Soheikh,

Nope. You've gotta first get the traffic to your server, and you have to do that through DNS.
# June 30, 2006 9:04 AM

soheilkh said:

tanks btompkins .
# July 1, 2006 5:22 PM

Sahil Malik said:

The words "sahil" and "agile" are together. Is there a hidden message here?
# July 11, 2006 7:10 AM

jim said:

when i request this page with url http://aaa.cc.codebetter.com/blogs/brendan.tompkins/archive/2006/06/27/146875.aspx . but it also open the same page , let us look at this code :
if (domainParts.Length > 2)

                       ctx.Server.Transfer("/explore/explore.aspx?q=" + domainParts[0]);
from this code ,the programe should open an other page ,but it is not ,why ?
# August 11, 2006 3:35 AM

Brendan said:

Jim, I think you're missing this line

if (ctx.Request.Path.ToUpper() == "/DEFAULT.ASPX")

Any page request will be ignored..
# August 11, 2006 9:41 AM

sub Domain « ali raza said:

# November 3, 2006 12:46 PM

Daily News Faq List said:

Brendan Tompkins demonstrates how to create unlimited subdomains with HTTP Modules in Community Server

# November 22, 2006 10:51 AM

VinayC said:

Wouldn't it work only if requesting url is for aspx page or some other asp.net resource? For other resources (such as html and images), IIS will try to handle the request; so asp.net runtime won't even get invoked.

# February 19, 2007 11:29 PM

Community Server Bits said:

Brendan Tompkins demonstrates how to create unlimited subdomains with HTTP Modules in Community Server

# March 12, 2007 11:03 AM

Pradeep said:

thank you sir for this valuble information

# July 5, 2007 6:07 AM

salman aa said:

Thanks a lot.

# July 16, 2007 11:14 PM

Paul said:

I am wondering how I can get the traffic to my server through the DNS. Can you please lead me to links for instructions how to do this? Also I didn't understand the point of the blank hostheader, what does this mean, any instructions about doing this?

# August 19, 2007 4:25 PM

Abishek.R.Srikaanth said:

What happens to the existing subdomains which are configured in the control panel, say the subdomains which are configured for mail and the controlpanel using subdomains
# November 28, 2007 2:48 AM

mohsen said:

thanks a lot but i have a question:

when i want to run my project and test this technique an error appear:

Could not load type 'SubdomainModule' from assembly 'vsub'

my assembly name is vsub and my class is SubdomainModule

can you say me what should i do for solve it

# March 1, 2008 10:44 AM

Govindaraj said:

Hai,

  What you have type inside the type parameter in the web.config file.

# March 28, 2008 3:29 AM

jockeyvn said:

Dear all,

Please help me, I cannot find subdomainhandler in cs file of Brendan Tompkins .

And parameter in Web.config make me confuse.

Please explain clearly.

Thanks in advance

# March 29, 2008 11:37 AM

Mojtaba said:

thanks i used it in my digital library

http://ent.ut.ac.ir/lib

# May 22, 2008 3:41 AM

manish said:

I am getting error while adding this :

<httpModules>

  <add name="SubdomainModule" type="Tompkins.Cs.Subdomains.SubdomainModule, Tompkins.Cs.SubdomainHandler" />

</httpModules> to my web config please help .

# May 22, 2008 8:28 AM

Ahmed said:

Why when i ues subdomain Module my session lost

# June 22, 2008 9:19 AM

how to creat a subdomain said:

Pingback from  how to creat a subdomain

# July 3, 2008 12:59 AM

Leave a Comment

(required)  
(optional)
(required)  

Enter the numbers above:
Add

About Brendan Tompkins

Brendan has been programming with .NET since the first public beta and is owner and operator of Port Technology Services, a consultancy company providing .NET application development services to the Maritime industry. In July, 2007, he was awarded the Microsoft MVP award for ASP.NET. He's also a proud co-founder of failed .COM startup Intrinsigo, and has had a hand in the failure of numerous other businesses. He currently runs CodeBetter.Com and Devlicio.us, and lives in Norfolk, Virgina with his wife Tiara and son Ian.

View Brendan's profile on LinkedIn

Check out Devlicio.us!