Here's how to properly configure custom error pages, including 404s and static file handling.
β
1. Enable Custom Errors in web.config
<configuration>
<system.web>
<customErrors mode="On" defaultRedirect="~/ErrorPages/GeneralError.html">
<error statusCode="404" redirect="~/ErrorPages/404.html" />
<error statusCode="500" redirect="~/ErrorPages/500.html" />
</customErrors>
</system.web>
</configuration>
π customErrors
mode
Options
Mode | Description |
---|---|
Off | Shows full error details, including stack trace. Use this only in development. |
On | Always shows the custom error page defined, even on the local machine. |
RemoteOnly | Shows detailed error to local requests, and custom page to remote users. Ideal for dev. |
π Tip: In production, use On or RemoteOnly to hide sensitive error details.
π§± 2. Handle Static File Errors (IIS Level)
By default, IIS handles static file errors (e.g., missing .jpg) and bypasses ASP.NET. To handle those too:
Add this under system.webServer
:
<system.webServer>
<httpErrors errorMode="Custom" existingResponse="Replace">
<remove statusCode="404" subStatusCode="-1" />
<error statusCode="404" path="/ErrorPages/404.html" responseMode="ExecuteURL" />
</httpErrors>
</system.webServer>
Explanation of httpErrors attributes:
errorMode="Custom"
: Enables your custom error pages.
existingResponse="Replace"
: Overwrites the existing IIS error with your own.
responseMode="ExecuteURL"
: Executes an ASP.NET page or serves a static file.
π― Example Folder Structure
/ErrorPages/
βββ 404.html
βββ 500.html
βββ GeneralError.html
Make sure these files are included in your project and set to "Copy if newer".
Summary
Task | Configuration Section |
---|---|
ASP.NET runtime errors | in system.web |
Static file errors (e.g., 404) | in system.webServer |
Show detailed errors locally | mode="RemoteOnly" |
Catch-all fallback | mode="defaultRedirect" |
If you're using MVC, you can create a custom ErrorController to catch all unhandled errors programmatically.
If you found this helpful, consider supporting my work at β Buy Me a Coffee.
Top comments (0)