Click here to Skip to main content
Click here to Skip to main content

Domain Forwarding with IHttpHandler

By , 9 Sep 2003
 

Introduction

In this article I describe how to use a custom HttpHandler as a domain-forwarder.

Background

With the Hostheader feature in IIS you can map many hostnames to one IP-Address. For example your IIS Server has the IP-Address 195.243.118.165. You or your ISP has some A-Records for this IP-Address.

www.mydomain.com A 195.243.118.165
www.virtualdomain1.com A 195.243.118.165
www.virtualdomain2.com A 195.243.118.165

Now, you have configured a website in IIS which responds to all these domains. The following image show a sample IIS configuration.

All requests to www.mydomain.com, www.virtualdomain1.com and www.virtualdomain2.com target the same website. Often you have to do such configurations because the amount of public IP-addresses is limited.

At this point you want to provide the user a different webpage depending on the used domain name. This sample application will provide a simple solution for this problem.

Using the code

Create a class in your ASP.NET application which implements the IHttpHandler. You have to implement one method and one property:

  • public void ProcessRequest (HttpContext)
  • public void IsReusable

Here is the sample code:

public class DomainHandler : IHttpHandler
{
    /// Implementing IHttpHandler
    public void ProcessRequest(HttpContext context) 
    {
        // Extract the host name from the request url
        // an look up the redirect url in the Web.config
        String redir = ConfigurationSettings.AppSettings
                              [context.Request.Url.Host];
        if (redir != null)
        {
            // check for valid redirect url, preventing loops
            if (RedirectIsValid(redir, context.Request.Url))
            {
                // redirect the user to the url found in web.config
                context.Response.Redirect(redir, true);
            }
            else
            {
                // display an error.
                context.Response.Write("<h1><font 
                   color=red>Error invalid DomainHandler 
                   configuration</font></h1><br>
                   <b>Please check your Web.config 
                   file.</b>");
            }
        }
    }

    // prevents possible redirect loops
    // it is not allowed to have an redirect url targeting its self
    private bool RedirectIsValid(String redir, Uri currentUri)
    {
        String val1 = redir.ToLower();
        String url = currentUri.AbsoluteUri.ToLower();
        String host = currentUri.Host.ToLower();

        if (val1 == url) { return false; } 
        if (val1 == ( "http://" + host)) { return false; }
        if (val1 == ("http://" + host + "/")) { return false; }
        if (val1 == host) { return false; }
        if (val1 == (host + "/")) { return false; }

        return true;
    }

    /// Implementing IHttpHandler
    public bool IsReusable
    {
        get
        {
            return true;
        }
    }
}
//

Points of interest

I decided to store my URL mappings in the web.config file as key-value pairs in the appSettings Section. Additionally you must register the new HttpHandler in your web.config file.

Sample web.config file is provided here:

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<appSettings>
<!--
Use as keys your full qualified host names.
As Value you provide a absolute url, you want to redirect to.
--> 
<add key="localhost" value="http://localhost/DomainForward/target1.htm" />
<add key="www.virualdomain1.com" value="http://www.myDomain.com/domain1" />
<add key="www.virualdomain2.com" value="http://www.myDomain.com/domain2" />
</appSettings>

<system.web>

<compilation 
defaultLanguage="c#"
debug="true"
/>

<httpHandlers>
<add verb="*" path="Default.aspx" 
    type="DomainFilter.DomainHandler, DomainFilter" />
</httpHandlers> 

</system.web>

</configuration>

In the path attribute in the httpHandlers section you specify a really existing filename which matches your "IIS-Defaultpage-Configuration".

In my sample application for simplicity I used a subweb, the default in Visual Studio. In a real world example, you would install the application in the root-web.

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here

About the Author

Andi Fleischmann
Web Developer
Germany Germany
Member
No Biography provided

Sign Up to vote   Poor Excellent
Add a reason or comment to your vote: x
Votes of 3 or less require a comment

Comments and Discussions

 
Hint: For improved responsiveness ensure Javascript is enabled and choose 'Normal' from the Layout dropdown and hit 'Update'.
You must Sign In to use this message board.
Search this forum  
    Spacing  Noise  Layout  Per page   
QuestionBind Domain to Application PagesgroupMorteza M17 Nov '12 - 4:05 
QuestionBlank pagememberthanks_in_advance12 Sep '12 - 23:57 
GeneralForwarding IPmemberOm Rudi29 Mar '09 - 6:38 
GeneralSmall improvement to RedirectIsValidmemberSameer Alibhai31 Jul '07 - 10:19 
GeneralDifference on IIS6 [modified]memberspdl200027 Oct '06 - 13:27 
GeneralMultiple URL Same Websitemembermukeshdas4 Oct '04 - 0:06 
GeneralRe: Multiple URL Same WebsitememberAndi Fleischmann4 Oct '04 - 0:39 
GeneralRe: Multiple URL Same Websitemembermukeshdas5 Oct '04 - 20:00 
Hi Andi,
Thanks for prompt reply from your side.
 
I am trying the following solution with domain forwarding, please let me whether this will work or not.
 
Suppose i have single estore which supports multiple companies and accessed as below in intranet scenario on developer machine.
 
For Company 'abc'
http://mukeshdas/estore?companyid = 'abc'
 
For Company 'xyz'
http://mukeshdas/estore?companyid = 'xyz'
 
in this scenario, domain forwarding will do nothing.
 
Now when this will be hosted in production along with ISA Server. Multiple url for different company will be mapped to single IP address of the web server as below.
 
COMPANY URL IP ADDRESS
===========================================
abc www.abc.com 10.92.17.22
xyz www.xyz.com 10.92.17.22
 
Now www.abc.com and www.xyz.com will hit to 'estore' site on 10.92.17.22. Here the domain forwarder will resolve the company based upon the url as below
 
www.abc.com => 10.92.17.22/estore?companyid = 'abc'
www.xyz.com => 10.92.17.22/estore?companyid = 'xyz'
 
Please let me know whether this approach will work or not? I have one more confusion here is, do i require any host header setting here?
Andi, i have full control of web server right now and all kind of hardware/software configuration option.
 
Thanks,
 
Mukesh Das
GeneralRe: Multiple URL Same WebsitememberAndi Fleischmann5 Oct '04 - 22:46 
GeneralVB.NETsussjtisdale25 Sep '04 - 12:10 
GeneralRe: VB.NETmemberDicke Berta30 Sep '04 - 4:34 
GeneralRe: VB.NETmemberjtisdale30 Sep '04 - 10:21 
GeneralMapping .html/.htm to .aspxmemberNeal Stublen11 Sep '03 - 20:55 
GeneralRe: Mapping .html/.htm to .aspxmemberNeal Stublen11 Sep '03 - 21:28 
Questionwhats the point?memberPhilip Fitzsimons11 Sep '03 - 2:52 
AnswerRe: whats the point?memberAndi Fleischmann11 Sep '03 - 5:59 
Questionhow about server.execute ?memberBecio17 Mar '03 - 23:00 
AnswerRe: how about server.execute ?memberBlake Coverett10 Sep '03 - 12:13 
GeneralApp inside AppmemberJ.M.Piulachs13 Mar '03 - 23:19 
GeneralRe: App inside AppmemberDa Bert14 Mar '03 - 18:01 
GeneralWhat if no file name? (was &quot;App inside App&quot;)memberRhy Mednick19 Sep '03 - 6:53 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Permalink | Advertise | Privacy | Mobile
Web01 | 2.6.130516.1 | Last Updated 10 Sep 2003
Article Copyright 2003 by Andi Fleischmann
Everything else Copyright © CodeProject, 1999-2013
Terms of Use
Layout: fixed | fluid