.htaccess:在RewriteRule之后检查文件是否存在

时间:2010-09-17 09:18:30

标签: .htaccess mod-rewrite

如果我的.htaccess中有一些规则:

RewriteCond %{REQUEST_FILENAME} -s [OR]
RewriteCond %{REQUEST_FILENAME} -l
RewriteRule ^.*$ - [NC,L]

RewriteRule ^assets/img(.*)/([a-zA-Z0-9-_\.]*)\.(.*)\.([a-z]{2,4})$ /assets/img$1/.$2.$4/$3.$4 [NC,L]

这会导致/assets/img/path/image.jpg> /assets/img/path/image.jpg

第二条规则:/assets/img/path/image.small.jpg> /assets/img/path/.image.jpg/small.jpg

现在我想检查small.jpg是否存在,所以我将最后一条规则替换为:

RewriteRule ^assets/img(.*)/([a-zA-Z0-9-_\.]*)\.(.*)\.([a-z]{2,4})$ /assets/img$1/.$2.$4/$3.$4 [NC]
RewriteCond %{DOCUMENT_ROOT}/assets/img$1/.$2.$4/$3.$4 !-f
RewriteRule ^assets/img(.*)/([a-zA-Z0-9-_\.]*)\.(.*)\.([a-z]{2,4})$ /assets/img/image.php?path=$1&file=$2.$4&template=$4 [NC,L,QSA]

但这不起作用。如果文件已被另一个RewriteRule重写,那么如何检查文件是否存在?

1 个答案:

答案 0 :(得分:0)

反之亦然:如果请求实际存在,则只将请求重写到目的地:

RewriteCond %{DOCUMENT_ROOT}/assets/img$1/.$2.$4/$3.$4 -f
RewriteRule ^assets/img(.*)/([a-zA-Z0-9-_\.]*)\.(.*)\.([a-z]{2,4})$ /assets/img$1/.$2.$4/$3.$4 [NC]
RewriteRule ^assets/img(.*)/([a-zA-Z0-9-_\.]*)\.(.*)\.([a-z]{2,4})$ /assets/img/image.php?path=$1&file=$2.$4&template=$4 [NC,L,QSA]

顺便说一句:如果您可以更具体,请不要使用.*。在这种情况下,[^/]+只能匹配路径段。