Saturday, January 26, 2008

Redirecting domain.com to www.domain.com through global.asax

OK this was a tricky one to solve, redirecting kadonk.com to www.kadonk.com using ASP.NET in C#. The solution came from lots of browsing, and many sources, and looks like this in global.asax (replace 'domain' with your own domain of course):


void Application_BeginRequest(object sender, EventArgs e)
{

// Don't do nothing while in test mode !
if (!Request.Url.Host.Equals("localhost")
&& !Request.Url.Host.ToString().Contains("www.domain.com")
&& Request.Url.Host.ToString().Contains("domain.com"))
{
string Result = string.Concat(
"http://",
Request.Url.Authority.Replace("domain.com", "www.domain.com"),
HttpContext.Current.Response.ApplyAppPathModifier(Request.Path),
Request.Url.Query);

HttpContext.Current.Response.Redirect(Result, true);
}
}




This will redirect kadonk.com to www.kadonk.com, but not any other domains we have, and it won't touch localhost (which may be funky). It will preserve Session variables and query strings, and should generally be nice and safe. You will note that I hardcoded "http://". I will fix that later to retain the protocol, but in any case I am using Matt Sollars GREAT WebpageSecurity package for SSL redirects!