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 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 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"];


    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);
        context.Response.Status = "404 Not Found";



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 (and any requests within) redirects successfully to

Google is happy. So I am happy.

No comments: