TMH
TMH

Reputation: 6246

How to stop this rewrite rule throwing a 500 error if the image doesn't exist

I've set up this rule so handle not found images

RewriteCond %{DOCUMENT_ROOT}%{REQUEST_URI} !-f
RewriteRule ^files/([a-zA-Z0-9]+)/([^.]*).(gif|jpe?g|png|bmp) /open/img/404/$1.jpg [NC,L]

So if the url is /files/offers/this/that/other/file.jpg, and the image doesn't exists, it will display the image /open/img/404/offers.jpg. This works great and well, unless offers.jpg doesn't exist, then it throws a 500 Internal Server Error.

Is it possible to make the rule only return the /open/img/404/something.jpg image if it is there, if not return /open/img/404/defaultImage.jpg?

Upvotes: 1

Views: 44

Answers (1)

anubhava
anubhava

Reputation: 785266

Yes it is possible, you can have rules like this:

# if /open/img/404/$1.jpg exists
RewriteCond %{DOCUMENT_ROOT}%{REQUEST_URI} !-f
RewriteCond %{DOCUMENT_ROOT}/open/img/404/$1.jpg -f
RewriteRule ^files/([a-zA-Z0-9]+)/([^.]+)\.(gif|jpe?g|png|bmp) /open/img/404/$1.jpg [NC,L]

# if /open/img/404/$1.jpg doesn't exist
RewriteCond %{DOCUMENT_ROOT}%{REQUEST_URI} !-f
RewriteCond %{DOCUMENT_ROOT}/open/img/404/$1.jpg !-f
RewriteRule ^files/([a-zA-Z0-9]+)/([^.]+)\.(gif|jpe?g|png|bmp) /open/img/404/defaultImage.jpg [NC,L]

Upvotes: 1

Related Questions