301 Moved Permanently

It's generally good practice to set up a DNS A-record to point to 'yoursite.com' and a CNAME that aliases 'www.yoursite.com' with 'yoursite.com'. Many users still think all addresses begins with www, and smarter/more lazy surfers simply skips the leading www and types in the top level domain name. If you don't do anymore about it, traffic analysis tools, logs, search engines and whatnot will see yourhost.com and www.yourhost.com as two separate sites. Reducing pagerank and giving more complex traffic analysis. External references and bookmarks will use both variants. Thus I usually redirects the www. variant to the shorter version. This is best done using a 301 HTTP redirection that instructs browsers and search engines that the page moved permanently to a new location, ie. to yoursite.com. The most common way is to write a HTTPModule and register it in web.config. The simpler way I present here is adding 10 lines of code in global.asa.cs.

public override void Init() {  
     BeginRequest += new EventHandler(App_BeginRequest);
void App_BeginRequest(object sender, EventArgs e) {  
     const string www = "www.";
     Uri requestUrl = Request.Url;
     bool hostBeginsWithWww = requestUrl.Host.StartsWith(www, StringComparison.OrdinalIgnoreCase);
     if (hostBeginsWithWww)
         string newLocation = requestUrl.GetLeftPart(UriPartial.Authority)
                                        .Replace(www, string.Empty)
                            + requestUrl.PathAndQuery;
         Response.Status = "301 Moved Permanently";
         Response.AddHeader("Location", newLocation);
m@kli.dk @klinkby RSS feed  GitHub