Sampson
Sampson

Reputation: 268434

Default (fallback) Image with .htaccess?

I'm curious if it's possible to use .htaccess to serve up a default image when a particular image is requested that doesn't exist (note: only image-requests should raise this behavior). I know I could do this with PHP by serving the images through a script, but I'm more curious if this can be done with .htaccess instead.

Suppose I request /thumbnails/010.gif, which doesn't exist. How could I get .htaccess to serve up /thumbnails/default.gif in its place?

Upvotes: 9

Views: 3816

Answers (3)

Boldewyn
Boldewyn

Reputation: 82804

If you send only images from this directory, you could utilize the ErrorDocument statement like this:

ErrorDocument 404 /thumbnails/default.gif

/thumbnails must be relative to your DocumentRoot.

I tested it with FF and it does as promised. However there could be issues with IE's "Don't display 404s that are smaller than some hundred KB" #%?$!

Upvotes: 1

Gumbo
Gumbo

Reputation: 655677

Since you just want to have it applied to /thumbnails/:

RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^thumbnails/ thumbnails/default.gif

Upvotes: 2

Travis
Travis

Reputation: 4078

I believe this will work for you. Place this .htaccess in your thumbnails directory and any URIs below /thumbnails that do not exist will direct to /thumbnails/default.gif

RewriteEngine On
RewriteCond %{REQUEST_FILENAME} -s [OR]
RewriteCond %{REQUEST_FILENAME} -l [OR]
RewriteCond %{REQUEST_FILENAME} -d
RewriteRule ^.*$ - [NC,L]
RewriteRule ^.*$ default.gif [NC,L]

Upvotes: 11

Related Questions