Setup a 301 permanent redirect using asp.net

June 08, 2011 - 08:32

A permanent 301 redirect is very usefull if you have recently moved or redesigned your website. Search engines will have references to your old pages and also any links from other websites may refer to your old pages. To keep any search engine ranking then you must add this redirect, and over time all the references will update to your new pages.

A simple redirect in asp.net can be done by adding the code below to your .aspx file.

Response.Status = "301 Moved Permanently"
Response.AddHeader("Location","newpage.aspx")


A common use is where you have updated your website to use SEO friendly urls. For example, your old pages used to be referenced with "viewdocument.aspx?DocumentID=231", and after you have optimised your website the new url would be "documents/my_document_title_ID231.aspx".

You would then place the code below in the "viewdocument.aspx" file to redirect to the new webpage, changing the contenturl string into the desired new url by looking up the title in the database and appending the DocumentID.

Dim DocumentID as Integer = Request("DocumentID")
Dim Title as String ="my document title"
'# This would be looked up in the database for the corresponding DocumentID

Title=System.Text.RegularExpressions.Regex.Replace(Title, "[^a-zA-Z0-9 ]", "").trim().replace(" ","-").tolower()
'# This removes all strange chracters and formats the title into a suitable url name.

Dim contenturl as string = Title & "_ID" & DocumentID & ".aspx"

Response.Status = "301 Moved Permanently"
Response.AddHeader("Location",contenturl)




© 2011 simplevb.net