htaccess: redirect 301 image if it doesn't exist

Viewed 31

in my htaccess file I should make sure that if a resource "a specific image" is not present it must do a 301 redirect with a different extension.

I try to explain myself better:

image: test.webp

if it does not exist, it must postpone:

test.jpg

Can such a thing be done? I apologize if I don't write an example of my code, but I really don't know just how to handle it in my htaccess.

Thank you

1 Answers

You can do this using mod_rewrite at the top of your .htaccess file:

RewriteEngine On

# Redirect "webp" images that do not exist to "jpg"
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^(.+)\.webp$ /$1.jpg [R=301,L]

For any request to a .webp file that does not exist, a 301 redirect is triggered to the same file but with a .jpg extension. eg. /foo/bar/does-not-exist.webp is redirected to /foo/bar/does-not-exist.jpg.

To also check that the target .jpg exists (before redirecting) you can add an additional condition. For example:

# Check that corresponding ".jpg" file exists before redirecting
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{DOCUMENT_ROOT}/$1.jpg -f
RewriteRule ^(.+)\.webp$ /$1.jpg [R=301,L]

However, I would question whether an external 3xx redirect is really the correct thing to be using here. This can be inefficient/slow if you have many such files. eg. Trigger an internal rewrite instead? For example, see my answer to the following question:

Related