Mod_Rewrite,在不同的文件夹中搜索不存在的文件



我有一个模板系统,我在其中使用图像和其他类型的文件,所以这里是一些模板和它们的图像的示例

/templates/template1/images/image1.jpg
/templates/template1/images/header/red/new/image1.jpg
/templates/template1/image2.jpg
/templates/template2/images/image2.jpg
/templates/template2/image2.jpg

现在,有时模板缺少图像或文件,在这种情况下,我想将用户重定向到"默认"模板,同时保留url的其余部分。

所以对于给出的例子,如果没有找到图像,应该将用户重定向到

/templates/default/images/image1.jpg
/templates/default/images/header/red/new/image1.jpg
/templates/default/image2.jpg
/templates/default/images/image2.jpg
/templates/default/image2.jpg

这是我的尝试,它在虚拟主机文件

中定义
RewriteEngine on
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_URI} !^/templates/default/(.*)$
RewriteRule ^/templates/(.*)/(.*) /templates/default/$2 [R]

this right now

将/templates/template1/images/image1.jpg重定向到/templates/default/image1.jpg,然后抛出500错误。

我在这里做错了什么?

我不知道为什么你得到了500,但是由于第一个.*的贪婪,ReqriteRule将有多个子目录的问题。

考虑请求/templates/template1/images/header/red/new/image1.jpg。如果这个文件不存在那么在^/templates/(.*)/(.*)中,第一个(.*)将匹配所有"template1/images/header/red/new",第二个(.*)将匹配"image1.jpg",因此您将被重定向到"/templates/default/image1.jpg"。

更好的规则:

RewriteRule ^/templates/[^/]+/(.*)$ /templates/default/$1 [R]

或者,如果您知道模板目录只能包含字母数字字符、下划线或连字符,那么这样做更好:

RewriteRule ^/templates/[a-zA-Z0-9_-]+/(.*)$ /templates/default/$1 [R]

最新更新