Rewritten 404/500 error page in subfolder doesn't resolve CSS/links

I have the following in my web.config file:

<httpErrors errorMode="Custom" existingResponse="Replace">
    <remove statusCode="404" subStatusCode="-1" />
    <remove statusCode="500" subStatusCode="-1" />
    <error statusCode="404" path="/ErrorPage.aspx?status=404" responseMode="ExecuteURL" />
    <error statusCode="500" path="/ErrorPage.aspx?status=500" responseMode="ExecuteURL" />

I'd like to rewrite the URLs when an error is encountered instead of redirecting to the error page as I've noticed people hitting a 404 page, get redirected to the 404 page and then keep refreshing the 404 page. I think rewriting is a better solution here.

The above config works if I go to (a 404). However, if I go to then I'm shown the error/404 page, however all the links and CSS are resolved from /foo instead of the web root so the page is displayed with no styles. (even CSS files from the /App_Themes folder, which is usually rewritten depending on sub-folder)

I have several URL rewrites in my web.config that rewrites some files in the root directory to appear like a sub-folder, and CSS/links are resolved correctly there:

        <clear />
        <rule name="Rewrite Products" stopProcessing="true">
            <match url="^p([0-9]+)/([_0-9a-z-]+).aspx" />
            <conditions logicalGrouping="MatchAll" trackAllCaptures="false" />
            <action type="Rewrite" url="Product.aspx?pID={R:1}&amp;pName={R:2}" appendQueryString="false" />

so a URL at displays the page at with all CSS/links correct.

Links and CSS (which I resolve with the ~ operator in ASP) are always displayed correctly for a valid sub-folder (so a link in the root of my site when viewed at will point to, not


Simply wrap your links with ResolveUrl and it will always resolve to the root.

hyperlink1.NavigateUrl = ResolveUrl("~/path/page.aspx")

You can also do this with stylesheets like this:

<link href="<%=ResolveUrl("~/resources/global.css")%>" rel="stylesheet" type="text/css" />

And with scripts like this:

<script src="<%=ResolveUrl("~/resources/myscript.js")%>" type="text/javascript"></script>

Need Your Help

Get File Bytes from Resource file in C#

c# resources byte

I used to store the resources in the actual project, but I've switched to using a resource file instead. Originally I could ready the bytes for a file, but I'm finding it difficult doing this with a