user2128200
user2128200

Reputation: 41

htaccess rewrite only if file doesn't exist

Using .htaccess mod rewrite, I would like to rewrite a url, check if that file exists, and if not rewrite again to another url using part of the original url which was removed during the 1st re-write.

For example, if the original url is this

/images/3001/zebra.jpg

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

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

Thanks very much, Phil

Upvotes: 4

Views: 1779

Answers (1)

Jon Lin
Jon Lin

Reputation: 143946

In the htaccess file in your document root, add these rules before whatever rules you may already have there:

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]

Upvotes: 3

Related Questions