Aug 29 2006

ASP.NET 301 redirect

Posted by admin under ASP.NET articles

When moving your pages from one place to another it is very tempting to handle old inlinks by creating a simple Response.Redirect( sNewPage, true );

This sure will work, but this type of redirect is a 302 and is meant for temporary relocations of pages. But your pages are permanently moved and therefore you should use a 301 Moved Permanently status code. This should preserve your search engine rankings for that particular page.

To solve it you could install some sort of redirect filter(ISAPI dll). I was looking into those type of solutions and found IISMods URL Rewrite Filter for IIS

Such a solution is very flexible and since it is a IIS filter it is possible to rewrite URL:s for all kind of filetypes, not only for aspx pages but say images (ex http://www.hello.com/*.gif could be transferred to http://www.hello.com/test/*gif ).

It is however not possible for everyone to install a ISAPI filter on their website, therefore I here present a solution on how you can achieve 301 redirects with pure ASP.NET code instead.

  In your old page you can write code such as

private void Page_Load(object sender, System.EventArgs e)
{
	Response.Status = "301 Moved Permanently";
	Response.AddHeader("Location","http://www.aspcode.net/newpage");
}

For me who wanted to redirect all calls to http://kbmentor.aspcode.net/whatever/it/could/be/foo.aspx to http://www.aspcode.net/articles/whatever/it/could/be/foo.aspx took and didn't have to think about pictures, cause they were "base" linked with the application took the idea one step further.

I created a new web application to install on kbmentor.aspcode.net. Basically it only contains a global.asax which handles Application_BeginRequest like this:

 

		protected void Application_BeginRequest(Object sender, EventArgs e)
		{
			string sOldPath = HttpContext.Current.Request.Path.ToLower();
			

			string sPage = "http://www.aspcode.net/articles/" + sOldPath;
			Response.Clear();
			Response.Status = "301 Moved Permanently";
			Response.AddHeader("Location",sPage);
			Response.End();
		}

ASPCode.net recommends