Apache: mod-rewrite to look up missing images in another directory

I am new to Apache mod rewrite. What I would like to achieve is this.

If an image (gif, jpg, png) is requested from an url and is not found there, it should automatically try to deliver this image from another directory.


Solution 1:

Try this:

RewriteEngine on
# if there's no file at the requested path..
RewriteCond %{REQUEST_FILENAME} !-f
# then, if it's an image file, try the other path:
RewriteRule /([^/]*\.(gif|png|jpg))$ /images/path/$1

This will act on every image file request that these rules are applied to; to restrict to just a specific "original" directory, then adjust as needed:

RewriteRule ^/old/images/path/([^/]*\.(gif|png|jpg))$ /images/path/$1

And if you're putting this in .htaccess or changing the RewriteBase, change accordingly.