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, 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 * to  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 *, 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:

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

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



About Brendan Tompkins

Brendan runs CodeBetter.Com. He was twice awarded MVP for Microsoft .NET, and is a founder and the CTO of Quick180.Com More about Brendan at
This entry was posted in Uncategorized. Bookmark the permalink. Follow any comments here with the RSS feed for this post.
  • vikas mhetre


    I can Use url rewriter for rewriting url . is this possible to create the subdomain by using url rewriting (my control panel configuration is IIs 7 )

  • milad seifoori

    Hi Guy .this post is very very usefull . i Create Standard Class with “SubdomainModule” name and put this to “App_Code”  folder , and  replace all codes with your SubdomainModule code but i have a problem with httpModul tag . when i test webapp on local or my vps appear this message  : ” Could not load file or assembly ‘Tompkins.Cs.SubdomainHandler’ or one of its dependencies ” what’s my wrong ? please Help me . Thanks for support. Best regards

  • Yash_rajput555

    hi brendan,
     if (domainParts.Length > 2)
                            ctx.Server.Transfer(“/explore/explore.aspx?q=” + domainParts[0]);
    can u tell me the importance of these lines?


  • Dorointernational

    ooooooooooooooooooo, Kaaaaaaaaayyyyyyyyyyyyyyyyyy

  • Rakeshcalls

    how to create subdomain in

  • sdfg@qwer.asdf


  • fghgfh


  • saiprakash

    I am getting error while adding this :

    to my web config please help .

  • jockeyvn

    This topic help update code sucessfully for long time, thank you

  • Zurmwqor


  • Diego Marques
  • dotnetguts

    Thanks it was helpful. A quick question, when we are using UrlRewriter will it create any problem?

  • jaiganesh

    in local host,i
    i have problem in web.config file(httpmodule) and also i want to know how to assign the httpapplication object.i am very new in pls tell me


    Even Pres Obama can code better than you Mr. Brendan Tompkins.

  • Muthukrishnan

    Could not load file or assembly ‘SubdomainModule.domain.SubdomainHandler’ or one of its dependencies. The system cannot find the file specified. (F:\Chandru\SubdomainModule\web.config line 17)

    The error occured. wat wil do?

  • Thomas

    I need to find a way to treat all subdomain urls coming into my domain as the actual path….

    My controls and App Code folder are not being recognized when the url uis entered as a subdomain – any ideas>>>

  • Adhok

    Good. But im confused

  • Izadpour

    so useful

  • Ahmed

    Why when i ues subdomain Module my session lost

  • manish

    I am getting error while adding this :

    to my web config please help .

  • Mojtaba

    thanks i used it in my digital library

  • jockeyvn

    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

  • Govindaraj


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

  • mohsen

    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

  • Abishek.R.Srikaanth

    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

  • Paul

    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?

  • salman aa

    Thanks a lot.

  • Pradeep

    thank you sir for this valuble information

  • VinayC

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

  • Brendan

    Jim, I think you’re missing this line

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

    Any page request will be ignored..

  • jim

    when i request this page with url . 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 ?

  • sahilmalik

    The words “sahil” and “agile” are together. Is there a hidden message here?

  • soheilkh

    tanks btompkins .

  • btompkins


    Nope. You’ve gotta first get the traffic to your server, and you have to do that through DNS.

  • soheilkh

    i can’t access to dns setup .
    is way that map all subdomain in iis setup

  • Aaron Erickson

    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!

  • btompkins

    Soheikh, have you setup your wildcard DNS to point to your website?

  • Soheilkh

    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

  • btompkins


    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.


  • Vince

    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?

  • Jeffrey Palermo
  • btompkins

    Steve, yes, I’ve often wondered the same… :) I’m actually quite suprised at the number of monkey posts!

  • Steve

    You can’t imagine how many times I’ve wondered what the best way to find all the posts about monkeys was on the site! :)