Wednesday, January 28, 2009

Setup 301 Redirect handler for all domains on an IIS Server

There are lots of different ways out there to redirect non-www domains to their correct www.domain.com equivalent.

For SEO purposes this is of the utmost importance because without redirects Google (and other search engines) assume data is being duplicated on two domains, and thus importance (and hence ranking) is distributed between them.

I wanted to create a way to make one single fix so that all domains setup on the server with the "www." only and not the non-www domain, would have their non-www equivilent redirected with a recommended 301 redirect.

This would be done with the Default Website in IIS, making use of UrlRewriter.net and a redirect.ashx handler. Setting up IIS to handle all extensions using these instructions we ensured that all requests are handled in the following way in the web.config:
<rewrite to="~/redirect.ashx?$1" url="^/(.*)$">
Here's the snippet from the handler itself:
public void ProcessRequest (HttpContext context) {
   string url = context.Request.ServerVariables["HTTP_HOST"];

   context.Response.Clear();

    if (!url.Contains("www."))    {
        url = "http://www." + url + "/" + context.Server.UrlDecode(context.Request.QueryString.ToString());

        context.Response.Status = "301 Moved Permanently"; 
        context.Response.AddHeader("Location", url);
    }
    else
    {
        context.Response.Status = "404 Not Found";
    }

    context.Response.End();

}

Now all the host headers without a binding to a website in IIS will find it's way here if the DNS is setup similarly, so domain.com (and any requests within) redirects successfully to www.domain.com.

Google is happy. So I am happy.

No comments: