January 23, 2019 10:26 by
Scott
I post this to remind myself how we got this working for both ASP.NET and static files, both for remote and local requests on IIS 7 and IIS 7.5.
<httpErrors> over <customErrors>
<customErrors> in web.config is a construct for specifying custom error pages for requests handled by ASP.NET. In other words, static files such as HTML files or directory (“friendly”) URLs are not handled.
<httpErrors> configures error pages in IIS itself, outside the web application. This handles all requests, whether they’re in fact handled by ASP.NET or IIS natively.
We ignore customErrors altogether and only use httpErrors.
Displaying a static HTML file
This is useful for error codes such as 500 where the ASP.NET web application in itself may suffer problems:
<httpErrors errorMode="Custom" defaultResponseMode="File">
<clear />
<error statusCode="500" path="Static\html\error.html"/>
</httpErrors>
Displaying an ASP.NET page
This displays an ASP.NET page when a 404 error occurs, without rewriting the URL (the visitor will still see the requested URL in the address bar):
<httpErrors errorMode="Custom" existingResponse="Replace">
<remove statusCode="404" subStatusCode="-1" />
<error statusCode="404" path="/Errors/404.aspx" responseMode="ExecuteURL"/>
</httpErrors>
Note that we skip the <clear /> element and simply remove the standard 404 handling (in order to avoid an exception caused by duplicate elements for the 404 status code).
Redirecting to another URL
ExecuteURL can only be used to execute an ASP.NET file within the same application. If we want to redirect to another application, or possibly an entirely different external URL, we use the Rewrite response mode with an absolute URL:
<httpErrors errorMode="Custom" existingResponse="Replace">
<clear />
<error statusCode="404" path="http://www.bing.com" responseMode="Redirect"/>
</httpErrors>
Make sure HTTP errors is enabled in IIS
For this to work you have to make sure the HTTP Errors feature is installed for IIS, otherwise you’ll just get an empty 404 response: