articles » archived » asp-net » redirect-404-errors

ASP.NET: Redirect 404 Errors

How to redirect 404 not found errors with ASPX Web Forms (.NET Framework).

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")) // if some paths were moved then this is a way to send them to a new location
			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" />

This site uses cookies. Cookies are simple text files stored on the user's computer. They are used for adding features and security to this site. Read the privacy policy.