Thursday, September 10, 2009

Redirecting Non-www Host to www Host in C#

Today I was tasked with redirecting all of the pages of a site (we'll call it site.com) without the "www" subdomain (site.com) to the one with the "www" (www.site.com). One of the things I wanted was that if the request was for "site.com/about.html" that it would be redirected to "www.site.com/about.html" not to "www.site.com/index.html". Below is the code I used in the Application_BeginRequest event handler in my global.asax file to accomplish this:
if (Request.Url.Host.ToLower() == "site.com") {

Response.Status = "301 Moved Permanently";
Response.AddHeader("Location", Request.Url.ToString().Replace("site.com", "www.site.com"));
Response.End();

}
This has the effect that was desired. Each individual page of the site will be redirected from "site.com" to "www.site.com".

No comments: