tags:

views:

50

answers:

2

What is the simplest way to redirect a web request to an ASP.NET application to a subdomain?

If a request comes into the URL http://somesite.com/foo.aspx, the new destination URL should be

  • http://www.somesite.com/foo.aspx or
  • http://blog.somesite.com/foo.aspx

How can you programmatically redirect the request to the subdomain, keeping the rest of the URL intact?

A: 

Depending on how many websites your IIS is running, you can do this by configuration manually pr. website - just add all the combinations to the application

OR you can develop a small "wildcard" redirector. Here comes the "programming answer" to a "server admin question":

Just make the default website on the IIS handle every "unknown" requested address. The incomming URL could be looked up in a "valid list of domains" and redirect apropriately.

We have such a mechanism running on our servers.

The easy version (short hack) would be to examine if there is WWW in the requested URL and if not, then try to add it to the request and redirect the client to that address.

Beware: this makes the client do a serverroundtrip which generates extra trafic. So if you have like 2000 hits pr. minut and half of them is without WWW, the hack is probarbly not the best idea.

Usefull answer?

BerggreenDK
+2  A: 

You could try something like this
A simple method that you can hook up to the Global.asax

Here's my Class

Imports System.Web.UI.HtmlControls        
Imports System.Web.UI        
Imports System.Web   

Public Class HelperPage  
    Inherits System.Web.UI.Page  

    ''# Force WWW     
    Public Shared Sub ForceWWW()  
        If Not GetServerDomain.StartsWith("www.") Then 
            HttpContext.Current.Response.Status = "301 Moved Permanently" 
            HttpContext.Current.Response.AddHeader("Location", "http://www." & GetServerDomain() & HttpContext.Current.Request.RawUrl)  
        End If 
    End Sub 

    Public Shared Function GetServerDomain() As String 
        Dim myURL As String = HttpContext.Current.Request.Url.ToString  
        Dim re As New Regex("^(?:(?:https?\:)?(?:\/\/)?)?([^\/]+)")  
        Dim m As Match = re.Match(myURL)  
        Return m.Groups(1).Value  
    End Function    
End Class 

and here's my call in the Global.asax

Protected Sub Application_BeginRequest(ByVal sender As Object, ByVal e As System.EventArgs)  
            HelperPage.ForceWWW()  
End Sub 

With that bit of code.. you will always be forced over to the WWW version of your website (providing that the Host Header in IIS has both the www and the non www version listed.)

rockinthesixstring