Htaccess overwrite only if the file does not exist

Using mod.htaccess mod rewrite, I would like to rewrite the URL, check if this file exists, and if it does not rewrite to another URL again, using the portion of the original URL that was deleted during the first rewrite.

For example, if the source url is

/images/3001/zebra.jpg

I would like to check if the file /images/cached/zebra.jpg exists and serve it if it exists.

And if not, I would like to rewrite in /image.php?id=3001

Thanks a lot, Phil

+4
source share
1 answer

In the htaccess file at the root of your document, add these rules before any rules that you may already have:

RewriteEngine On # cached copy exists RewriteCond %{REQUEST_URI} ^/images/[0-9]+/(.+)$ RewriteCond %{DOCUMENT_ROOT}/images/cached/%1 -f RewriteRule ^ /images/cached/%1 [L] # cached copy doesn't exist RewriteCond %{REQUEST_URI} ^/images/([0-9]+)/(.+)$ RewriteCond %{DOCUMENT_ROOT}/images/cached/%2 !-f RewriteRule ^ /image.php?id=%1 [L] 
+3
source

All Articles