Mugshot

Hey I'm Lee. My blog was put up to house useful nuggets I could refer back to, document my learning curves on new technologies and house tutorials I write for Umbraco and other .NET stuff.

All thoughts and comments on here are my own, and in no way reflect my employer - I also take no responsibility for spelling, grammar or terminology, so read at your own risk!

Blogs I Read

Sites I Like

Dynamically 301 Redirect 404 Page Not Found In ASP.NET

I have been building our new content management system, and I knew that our first site to be using it would need have a lot of pages 301 redirected as we are going to change the file structure and pages names (And the old site has has a lot of SEO done).  So I thought it would be a great ‘Admin Tool’ to be able to add the old and new pages into a table and if a 404 was served (One of the old pages) check against the pages in the database and 301 redirect the page to the new one.

So I made a simple table which held the OldURL & NewURL [more]

bdui

Then in the ‘Admin’ section I just created a very simple page which let me add in the pages and showed a list of the old URLs and where I wanted them 301 redirected

uiadmin 

Now to catch the 404 and 301 redirect to the new page I use the Global.asax file – I simply check on Application_Error to see if the page causing the error is if the page is in our list of old URL’s I 301 redirect to the new page (I literally just loop through a SQLDataReader) like so

Sub Application_Error(ByVal sender As Object, ByVal e As EventArgs)
    Using Reader As SqlDataReader = **MyDataReaderReturningAllUrls**
        If Reader.HasRows Then
            While Reader.Read()
                If HttpContext.Current.Request.RawUrl.ToString() = Reader("OldURL").ToString() Then
                    HttpContext.Current.Response.Clear()
                    HttpContext.Current.Response.Status = "301 Moved Permanently"
                    HttpContext.Current.Response.AddHeader("Location", "http://mywebpage.com" & Reader("NewURL").ToString())
                    HttpContext.Current.Response.End()
                End If
            End While
        End If
    End Using
End Sub

From what I have read its not the best way to do this by grabbing the page in the Application_Error, and I will look for a more efficient way in the next few days – But it solves as very annoying problem for any web company who know the headache of 301 redirecting numerous pages on an old site to a new structure to keep the PageRank and inbound links intact.

Hope someone finds this useful :)

Back to top