Search code examples
.htaccesshttp-status-code-404

htaccess Redirect when 404


I have a subdirectory called /marker, in it are some png files. Now I want the file /marker/standard.png to be returned whenever an attempt is made to call a png that does not exist. In other words: If, for example, /marker/doesntexist.png is called (which doesn't exist), /marker/standard.png should be delivered.

Sounds quite simple, but several attempts with RewriteRule or ErrorDocument failed.

Any ideas? tia


Solution

  • You can do the following to serve /marker/standard.png if another .png file in the /marker directory is requested that does not exist.

    This uses mod_rewrite and should go near the top of the .htaccess file in the document root.

    RewriteEngine On
    
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteRule ^marker/(?!standard\.png$).+\.png$ marker/standard.png [L]
    

    I took the extra step to exclude requests for standard.png itself (using a negative lookahead), in case this doesn't exist for some reason.

    Note that this is a case-sensitive string comparison. eg. Only .png files are matched, not .PNG.

    This naturally results in a 200 OK response when standard.png is served. If you still need a 404 Not Found status then use ErrorDocument instead (see the next section).


    Using ErrorDocument

    You also mentioned the use of an ErrorDocument directive. This is another solution, although it will result in a 404 HTTP response status, which may or may not be desirable.

    For example, in order to restrict this ErrorDocument just to the /marker subdirectory then create an additional .htaccess file in this subdirectory with the following:

    ErrorDocument 404 /marker/standard.png
    

    This will naturally serve standard.png for any non-existent request to the /marker subdirectory. To restrict this to .png requests only then wrap the ErrorDocument in an <If> expression. For example:

    <If "%{REQUEST_URI} =~ /\.png$/">
        ErrorDocument 404 /marker/standard.png
    </If>