Search code examples
apache.htaccessmod-rewrite

Replace images that does not exist in htaccess


After series of search on stackoverflow, i got these two working htaccess codes, however, i'm confused which one is better.

Actually both works fine but is there any difference in performance or speed?

<FilesMatch "\.(jpg|jpeg|png|gif)$">
ErrorDocument 404 "/no_profile_picture.png"
</FilesMatch>

and

RewriteEngine On
RewriteCond %{REQUEST_URI} \.(jpg|jpeg|gif|png|ico)$ [NC]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d  
RewriteRule .* /no_profile_picture.png [L]

Solution

  • Both directives will serve the core purpose of showing /no_profile_picture.png when an image with jpg|jpeg|gif|png|ico extensions is not found inside your site root. However there is a subtle difference.

    <FilesMatch "\.(jpg|jpeg|png|gif)$">
    ErrorDocument 404 "/no_profile_picture.png"
    </FilesMatch>
    

    This directive will also return 404 (Http NotFound) status to browser/client but the other block will still return 200 (Http OK) status back to clients. So I suggest going with FilesMatch block for correctly showing desired non-found image and returning 404 to clients.