Santry Technology Solutions, Content Management, DotNetNuke, SharePoint Consulting
Register | Login
Tuesday, October 07, 2008

Sections
  
About Us
  
Partners
Downloads
  
 WWWCoder.com Resource Directory

404 Not Found Redirection
1/18/2004 11:22:43 AM

Recently we had a Website that was redone from a large static site to a dynamically driven site in ASP.Net. The original site was heavily indexed by the major spiders on the Web, we did not want to lose the reference links in the engines and wanted to make sure the link clicked on would go to an appropriate paged in the site. In this article we cover how to create a document mapper so the old URL is redirected to the new related page within the new site.

In this article I will cover creating a custom 404 handler for your ASP.Net site. There are tutorials out there that cover doing this, but in this article we add an additional feature where we create a lookup table that looks up the page that doesn't exist anymore and then redirect the request to an appropriate page related to the missing content.

On one project I was working on, we did a massive reorganization of the company's Web site. We consolidated several domains into one massive corporate Website. As a result of this most of the links to pages within the site were lost. So any results that would come up in the search engines would be broken and return a 404 error. We didn't want to just present the browser with a generic error page, we wanted something with some intelligence that knows what the page was they were going to and then redirect them to an appropriate page within the new site structure.

First thing we did was to create a table to handle our lookups for the redirect. This lookup table contained two fields, one was for the old URL string, and another for the ID of the new page (since the new Web site is dynamically created from database data all we need is the ID of the page).

OldUrl NewTabId
/careers.htm 23
/aboutus.htm 25

Table for URL lookup to new ID

Now that our table is created, we need to populate the table for the lookup to handle a 404 not found error. As you can see in the table we have old absolute path of a page, ex. "/careers.htm", which equates to a TabID so our custom handler can lookup the page and redirect the request to the appropriate page being generated by our application.

Option Strict On
Imports System.Data
Imports System.Configuration
 
Public Class _404Handler
    Inherits System.Web.UI.Page
 
#Region " Web Form Designer Generated Code " 
#End Region
 
    Private Sub Page_Load(ByVal sender As System.Object, ByVal e As _
                 System.EventArgs) Handles MyBase.Load
        'Put user code to initialize the page here
        Try
            Dim strQuery As String = Request.ServerVariables("QUERY_STRING")
            If strQuery <> "" Then
                'Now we'll remove the stuff we don't need.
                strQuery = strQuery.Replace("404;http://", "")
                'Get rid of the domain name since we're dealing with multiple domains.
                Dim intSlashPosition As Integer = strQuery.IndexOf("/")
                strQuery = strQuery.Remove(0, intSlashPosition)
                ' now do a lookup in our table to find out if there is a related page.
                Dim NewURL As Integer = DoURLLookup(strQuery)
                If NewURL <> -1 Then
                    Response.Redirect("/DesktopDefault.aspx?TabID=" & NewURL.ToString)
                Else
                    'if we don't have any, just send them to the home page of the site.
                    Response.Redirect("/")
                End If
            Else
                Response.Redirect("/")
            End If
        Catch ex As Exception
            Response.Redirect("/")
        End Try
    End Sub
    
    'This function performs the lookup in the database to find a related page for the broken link.
    Function DoURLLookup(ByVal inURL As String) As Integer
        Dim cnn As New SqlConnection(ConfigurationSettings.AppSettings("connectionString").ToString)
        Dim myCommand As SqlCommand = New SqlCommand("SELECT NewTabID FROM " & _
             "NotFoundLookup WHERE OldURL = '" & Replace(inURL, "'", "''") & "'", cnn)
        cnn.Open()
        Dim result As SqlDataReader = myCommand.ExecuteReader(CommandBehavior.CloseConnection)
        If result.Read Then
            Dim TabID As Integer = CType(result("NewTabID"), Integer)
            cnn.Close()
            Return TabID
        Else
            cnn.Close()
            Return -1
        End If
    End Function
 
End Class

Now that we have our Web form class, all we need to do now is configure IIS to use this page as the custom 404 error handler. To configure this page, go to Computer Management and open the Internet Information Services node. From here, find the Web site you want to apply the handler to. Right click on the site and select properties. From here click on the Custom Errors tab, scroll down and find the 404 error code, change the properties of the error handler to select URL, and then enter in the absolute path for the handler, so for example if our 404Handler.aspx is in the root directory, enter in "/404Handler.aspx" in this dialog.

You can also configure a 404 handler within the web.config, but in order to do this you then need to make sure ASP.Net processes all document type requests going to the server. By configuring the custom handler in IIS you will not need to do this. Another option would be to create a custom HTTPModule to intercept the request and handle accordingly, but again, this method would require that all page types be processed by ASP.Net.

By: Patrick Santry, Microsoft MVP (ASP/ASP.NET), developer of this site, author of books on Web technologies, and member of the DotNetNuke core development team. If you're interested in the services provided by Patrick, visit his company Website at Santry.com.


Page Options:
format for printing  Format for Printer
email article  Email Page
add to your favorites   Add to Favorites
How would you rate the quality of this content?
Poor - - Excellent
Comments?
Overall Rating:
Comments Left:
Left on 12/4/2007 8:51:47 AM by Anonymous
Comments: mal
Left on 11/11/2007 7:52:49 PM by Anonymous
Comments: Hello! Good Site! Thanks you! fjuhbzhhirrsb
Left on 9/20/2007 8:57:49 AM by Anonymous
Comments: I use this on www.meli.se and it works great!
No ratings available.
Left on 9/13/2006 8:51:20 AM by Anonymous
Comments:
Left on 2/15/2006 5:06:32 PM by Anonymous
Comments: Exactly what I was looking for, thanks!!
No ratings available.
Left on 2/4/2005 7:42:40 PM by Anonymous
Comments: sucks!
Left on 10/14/2004 9:57:17 AM by Anonymous
Comments: Including the redirect in the try-catch throws an eror (in VB.NET anyway). You need to move the redirect out of the try to make it work.

Configuring IIS only works to catch 404s for non-aspx pages. For that, you need to use web.config. However, this use was for .html pages only, so it would work.
No ratings available.
Left on 7/22/2004 3:13:11 PM by Anonymous
Comments: Great article, thanks !
Left on 6/23/2004 6:02:38 PM by Anonymous
Comments: This rocks!  Thank you for sharing!
Left on 6/23/2004 2:35:18 PM by Anonymous
Comments: http://sitedirector.nc-software.com has a neat utility for this
No ratings available.
Left on 4/26/2004 4:32:01 AM by Anonymous
Comments: Very cool.  Replaces my ASP version nicely!  Thanks!
Left on 4/8/2004 5:42:50 PM by Anonymous
Comments: Just what I was looking for, Great
Left on 2/3/2004 2:27:56 PM by Anonymous
Comments: Yes it does work. You're probably doing something wrong.
No ratings available.
Left on 2/3/2004 2:21:12 PM by Anonymous
Comments: From here click on the Custom Errors tab, scroll down and find the 404 error code, change the properties of the error handler to select URL, and then enter in the absolute path for the handler, so for example if our 404Handler.aspx is in the root directory, enter in "/404Handler.aspx" in this dialog.
This does Not work
See Post http://www.asp.net/Forums/ShowPost.aspx?tabindex=1&PostID=453138

Left on 2/1/2004 4:14:16 PM by Anonymous
Comments: What does one do if on a shared hosting service, where one does not have access to extension mappings nor to to the custom error on IIS?
Left on 1/30/2004 11:23:03 AM by Anonymous
Comments: I am a novice with a little bit of coding experience in C and I was able to understand the concept and procedures. Many developers leave us entry-levl guys out when they create articles. Thanks to the author for sharing the wealth.
Left on 1/28/2004 11:27:01 PM by Anonymous
Comments: Someone at Microsoft should read this and make the Knowledge Base redirect old links to current pages. There are thousands of solutions to problems in Google Groups that have an old KB link, click on them and you get "the requested page is unavailable" a dead end instead of an instant answer. Nobody at Microsoft gets this concept, not surprising.
No ratings available.
Left on 1/28/2004 9:49:45 AM by Anonymous
Comments: The one reason is in order to use a HTTPHandler, you need to then map all extensions (since the files could be anything from htm, pdf, to images) so they are processed by ASP.Net. This extra bit overhead (even if slight) seemed to be something that wasn't neccessary to do since we could accomplish it by just mapping the custom error in IIS.
No ratings available.
Left on 1/28/2004 9:42:02 AM by Anonymous
Comments: Is there a particular design reason you used a custom 404 error handler instead of moving the same logic into an HTTPHandler?
Left on 1/27/2004 10:47:28 PM by Anonymous
Comments: Comments from the following blog: Patrick Santry's Blog, located at: http://blogs.wwwcoder.com/psantry/archive/0001/01/01/231.aspx
No ratings available.
  

 Latest Articles
  

 Latest News
  

 

Spotlight
Syndication

 


 


Digg This
 


DotNetNuke Platinum Benefactor

  
 

 Terms Of Use | Privacy Statement
 Copyright 2008 - Santry Technology Solutions, Box 172, Girard, PA 16417, (814) 774-0970