Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

404 redirect for pages only not images

I am working with an asp.net mvc application. I have the following entry in web.config to handle 404's

    <httpErrors errorMode="Custom" existingResponse="Replace">
<remove statusCode="404" subStatusCode="-1" />
<error statusCode="404" path="/Error/Error404" responseMode="ExecuteURL" />
</httpErrors>

This works fine for when pages are requested, it redirects to my 404 view. However for missing images it also redirects to the 404 page ie. the response for the image is the 404 page.

As this is a performance issue, is there any way I can alter the above so that only 404 from "pages" and not resources such as images trigger a redirect to the 404 page?

like image 682
amateur Avatar asked Sep 02 '25 07:09

amateur


2 Answers

I know this is an year old question, however I just came across the same problem, and I was able to come up with a solution based on what I was using in htaccess.

The below solution basically checks if the file has an image extension, and it isn't a file and isn't a directory. After that it serves up an image file that I use to identify missing images.

<rule name="404 Images" stopProcessing="true">
    <match url=".*" ignoreCase="true" />
    <conditions>
        <add input="{URL}" pattern="^.+\.(jpg|jpeg|png|gif|ico)$" ignoreCase="true" negate="false" />
        <add input="{REQUEST_FILENAME}" matchType="IsFile" ignoreCase="true" negate="true" />
        <add input="{REQUEST_FILENAME}" matchType="IsDirectory" ignoreCase="true" negate="true" />
    </conditions>
    <action type="Rewrite" url="/design/images/404.png" />
</rule>
like image 152
imvain2 Avatar answered Sep 05 '25 01:09

imvain2


You could disable runAllManagedModulesForAllRequests:

<system.webServer>
    <modules runAllManagedModulesForAllRequests="false" />
    ...
</system.webServer>

Of course now you're gonna see IIS default 404 page for broken images since static resources will be directly served by the static handler and not going through the managed pipeline.

like image 31
Darin Dimitrov Avatar answered Sep 05 '25 02:09

Darin Dimitrov