htaccess rewrite only if file doesn't exist

泪湿孤枕 提交于 2020-01-01 06:09:13

问题


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


回答1:


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]


来源:https://stackoverflow.com/questions/15182769/htaccess-rewrite-only-if-file-doesnt-exist

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!