我有一个模板系统,其中我使用图像和其他类型的文件,所以这里是一些模板及其图像的示例
/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
现在,有时模板会丢失图像或文件,在这种情况下,我想将用户重定向到“默认”模板,同时保留网址的其余部分。
因此,对于给出的示例,如果未找到图像,则应将用户重定向到
/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]
现在这个
将/templates/template1/images/image1.jpg重定向到/templates/default/image1.jpg,然后抛出500错误。
我在这里做错了什么?
答案 0 :(得分:1)
我不确定你为什么要获得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]
尽量使正则表达式尽可能具体。