Forum Moderators: phranque
which is now closed, so I cannot post a reply there, can anyone help, please?
The following code was posted to replace a missing image with a default one:
Options +FollowSymLinks
RewriteEngine on
# Redirect missing catalog images to a default image. Let other missing resource requests 404 normally.
RewriteCond %{REQUEST_URI}!-U # if requested resource doesn't exist
RewriteRule ^catalog_image_path/.*\.gif$ /default_image_path/default.gif [L] # redirect to default image
This, in my understanding, replacing missing images only in the specified directory. However, what I need to do is replace all missing images be they .gif, .jpeg whichever directory they may be in or even if they are on a different server(or website). Is there any way I can achieve this?
Thanks In Advance.
RewriteRule ^catalog_image_path/.*\.gif$ /default_image_path/default.gif [L] # redirect to default image
to
RewriteRule \.(gif¦jpg¦jpeg)$ /default_image_path/default.gif [L] # redirect to default image
That should work (I don't know mod_rewrite too well - but I do understand regular expressions :))
Yes, grahamstewart's got it.
Some more info, though: In the original, I added comments on the code lines to illustrate the flow, but this will cause warnings in most Apache installs. Move the comments to their own lines as shown below or just remove them entirely.
Options +FollowSymLinks
RewriteEngine on
# Redirect missing catalog images to a default image. Let other missing resource requests 404 normally.
#
# if requested resource doesn't exist
RewriteCond %{REQUEST_URI} !-U
# redirect to default image
RewriteRule \.(gif¦jpg¦jpeg)$ /default_image_path/default.gif [L]
This code uses the "-U" hook to determine if a URL exists on the site. As such, it is fairly inefficient; see the note in the original thread. There's no way around the inefficiency, so make sure the RewriteRule is as exclusive as it can be. If the RewriteRule does not match, then the RewriteCond will not be evaluated, saving a wasted URL-exists lookup. Also, place this code as close to the top of your .htaccess as possible - It will be processed for every image request!
If you have a large, busy, image-intensive site, monitor it closely for perfomance issues after installing this code. Also, make sure you have made your images cacheable by including correct cache-control headers. This will reduce demand on the image-exists lookups for any images which are used repeatedly (spacer gifs, logos. etc.).
As always, replace the broken vertical pipe "¦" characters above with the one from your keyboard.
HTH,
Jim