How to Redirect a Subdomain While Preserving the original URL with Server.Transfer

Discussion in 'Tutorials' started by RayH, Apr 18, 2011.

  1. RayH

    RayH DiscountASP.NET Lackey DiscountASP.NET Staff

    This post is a tutorial for customers that have either purchased the Unlimited Subdomain or SSL Addon and represents a summary of information I was able to collect on the forums. It supplements the information already provided in this knowledgebase article.

    [Optional] Set the default document using the IIS Tools in your Control Panel to a redirect script such as redirect.aspx.

    Use the following sample code in the Page_Load method of your code behind file (e.g. redirect.aspx.cs):

    C# Example:

    Code:
    if (Request.ServerVariables[“SERVER_NAME”].ToString() == “mysubdomain1.mydomain.com”)
      Server.Transfer(@”~/subdirectory”);
    else if (Request.ServerVariables[“SERVER_NAME”].ToString() == “mysubdomain2.mydomain.com”)
      Server.Transfer(@”~/subdirectory”);
    else
      Server.Transfer(@”~/subdirectory”);
    Using the above code will preserve the original URL.

    For example, when a user visits the site http://sub1.mydomain.com/default.aspx, it will show http://sub1.mydomain.com/default.aspx. If he/she visits http://sub2.mydomain.com/default.aspx, it will show http://sub2.mydomain.com/default.aspx.

    A few notes regarding Server.Transfer:

    1) It conserves server resources.
    2) It can only be used on sites hosted on the same web server. It is unable to perform redirects to an external site. You will need to use Response.Redirect instead.
    3) It preserves the original URL.
    4) It has second method call which will also preserve an existing query string, although, it is a bit buggy. For more information, please go to http://support.microsoft.com/default.aspx?id=kb;en-us;Q316920.

    Please note that this information was taken from an article written by Karl Moore. You can view the article he wrote here: http://www.developer.com/net/asp/article.php/3299641/ServerTransfer-Vs-ResponseRedirect.htm
     

Share This Page