Need a simple CRM and Project Management system?
Check out JobNimbus - CRM for Contractors and Service Professionals.

ASP.NET 301 Redirect for Search Engine Compliant Redirects

There are lots of ways in ASP.NET to redirect to a different page. When a page has been indexed by a search engine at a specific URL, you will be getting traffic from that search engine to that URL. But what if you need to move this content somewhere else or need to change the URL of the page?

If you change the content of the page or URL to the page, then you will automatically lose all of that search engine traffic because the search engine will find that the content has changed (or the page does not exist), so it will stop sending content to that URL. That is something you never want to happen because it is so hard to build ranked pages in search engines like Google.

A common mistake is to just place a simple redirect statement in the page load event of the page like this:

// Does an HTTP 302 (Moved Temporarily) redirect
Response.Redirect("http://www.someurl.com/somedir/somepage.aspx");

But this does a 302 redirect that tells the search engine the content is only temporarily moved. So the search engine will assume that the content is still here but is just not available currently and will continue to hit the old invalid URL.

Instead, you need to redirect with an HTTP 301 status code which tells the search engine that the content has permanently moved to the new URL. This will allow the search engine to set the new link as the location of the content and the old URL will not be hit anymore.

Unfortunately, there is no simple overload or built-in method that does a 301 redirect. But you can manually set the HTTP status code with just a few lines of code. If you are using ASP.NET 3.5 or lower, then you can provide a 301 redirect with this method:

/// <summary>
/// Redirects to the URL specified with an HTTP status code of 301.
/// 
/// </summary>
/// <param name="url">The URL to permanently redirect to.</param>
public void Redirect301(string url)
{
    Uri absoluteUri = null;
    if (!Uri.TryCreate(url, UriKind.Absolute, out absoluteUri))
    {
        throw new Exception("Redirect URL must be an absolute URL.");
    }

    Response.Clear();
    Response.Status = "301 Moved Permanently";
    Response.AddHeader("Location", url);
    Response.End();
}

NOTE: Make sure to use the entire, fully qualified URL to the new page. Do not use a relative URL. It must be an absolute path.

If you are using ASP.NET 4.0 or higher, there is now a built-in redirect method that you can use in a single line of code. To redirect 301 with ASP.NET 4.0 or higher, you can use this code:

// does an HTTP 301 redirect in ASP.NET 4.0 or above
Response.RedirectPermanent("http://www.mynewurl.com/mynewdir/mynewpage.aspx");