用mod_rewrite改变文件名?

时间:2012-10-30 19:24:43

标签: apache mod-rewrite

如果您要通过/foo/index.html访问文件/bar/index.html,这很容易重写:

RewriteRule ^bar/(.*)$    foo/$1 [L] # <-- Leaves URL the same, but gives content of foo/

但这意味着/foo/index.html/bar/index.html现在都可以访问内容。有没有办法现在禁止通过/foo/index.html进行访问?刚做:

RewriteRule ^foo/(.*)$    bar/$1 [R=301,L] # <-- Change the URL if accessed via /foo
RewriteRule ^bar/(.*)$    foo/$1 [L] # <-- Leaves URL the same, but gives content of foo/

导致重定向循环。有没有办法表明“将foo重定向到bar,除非URL已经'/ bar'”?

1 个答案:

答案 0 :(得分:0)

是的,但你需要对%{THE_REQUEST}之类的东西进行检查,否则你的两条规则会不断改变对方的重写和循环。如下所示:

# this is the rule you already had:
RewriteRule ^bar/(.*)$    foo/$1 [L]

# this is the rule that externally redirects
RewriteCond %{THE_REQUEST} ^[A-Z]{3,9}\ /foo/
RewriteRule ^foo/(.*)$ /bar/$1 [L,R=301]

%{THE_REQUEST}变量进行检查可确保为/foo生成实际请求,而不是内部重写的请求。