ASP.NET Redirect 404 Errors

ASP.NET makes it easy to retrieve the url that caused the 404 (not found) error and then it is easy to redirect to an appropriate replacement.

First, modify the web.config file.

Add a customErrors tag. This is for when a file is not found.

	<customErrors mode="RemoteOnly" defaultRedirect="/error404.aspx" redirectMode="ResponseRewrite">
		<error statusCode="404" redirect="/error404.aspx"/>

Add a httpErrors tag. This is for when a path/directory is not found.

	<httpErrors errorMode="Custom">
		<remove statusCode="404" subStatusCode="-1" />
		<error statusCode="404" prefixLanguageFilePath="" path="/error404.aspx" responseMode="ExecuteURL" />

Now, create an error404.aspx WebForm and modify it as follows.

// error404.aspx.cs
public partial class error404 : System.Web.UI.Page
	protected void Page_Load(object sender, EventArgs e)
		string s = (Request.QueryString["aspxerrorpath"] ?? Request.RawUrl);
		if (s.StartsWith("/SomePath"))
			Response.Redirect("" + s, true);
			Response.StatusCode = 404;
			divErrorPath.InnerHtml = "<b>" + s + "</b> not found";
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="error404.aspx.cs" Inherits="namespace.error404" %>

<!DOCTYPE html>

<html xmlns="">
<head runat="server">
	<title>404 ERROR (NOT FOUND)</title>
	<div id="divErrorPath" runat="server" />