Chris Athanasiadis
Chris Athanasiadis

Reputation: 390

Apache show a default image when there is a 404 error under a specific URL pattern

In a pure client based web app I need to show a background image that sometimes doesn't exist. Is there a way of 'forcing' Apache to serve an image when a specific URL pattern returns a 404 error?

The URL pattern that might return a 404 is:

http://host/assets/user-images/xxxxx.jpg

Where I want to serve the image:

http://host/assets/user-images/default.jpg

NOTE:

I already use a .htaccess

RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^ index.php [QSA,L]

Upvotes: 4

Views: 1956

Answers (1)

Nidhi
Nidhi

Reputation: 888

Add the following in the file "/assets/user-images/.htaccess"

RewriteCond %{REQUEST_URI} ^/assets/user-images/(.*)\.jpg$ 
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^(.*)$ default.jpg

The first RewriteCond will check whether the incoming request is for a jpg file under /assets/user-images/ or not and the second RewriteCond with -f option will check whether the requested file exists or not. If it does not exists the RewriteRule will serve the default image. The end user will still see the URL of the original image but the default image will be served. If the original image file exists this rule will not execute.

Upvotes: 7

Related Questions