HTTP 301 Redirect in ASP.Net for an Entire Directory

Having recently moved my DasBlog tech blog from one domain to another I wanted an easy way to redirect all the traffic from the old domain, to the new one.
My shared hosting provider doesn’t provide directory level redirects (although this can be done in IIS) – only domain level.
There are also plenty of examples out there for how to redirect a single page – typically Default.aspx. What I wanted was true SEO friendly Url for Url permanent HTTP 301 redirection for every page and service in the blog.Since the blogging engine and directory contents were the same all I needed to replace was the name portion of the domain name for the incoming Urls, redirecting them to the same resource, but on the new domain.
So I knocked to together an HTTP Handler that looks like this.
namespace DotBits.Handlers{   public class RedirectHandler : IHttpHandler  {      public void ProcessRequest(HttpContext context)     {        context.Response.Status = "301 Moved Permanently";        string url = context.Request.Url.ToString().Replace("dotbits", "58bits");        context.Response.AddHeader("Location", url);      }

      public bool IsReusable     {        get { return false; }     }    }}
And then a reference to the handler with the correct path statement in the Web.config file.
<system.web>   <httpHandlers>     <add verb="*" path="blog/*.*" type="DotBits.Handlers.RedirectHandler"/>   </httpHandlers></system.web>
Presto. Works for all registered ASP.Net resource types; .aspx, .asmx, .axd etc.

Category