NGINX重写/位置正则表达式重定向/index.html $ - > /

时间:2015-07-07 15:49:33

标签: regex redirect nginx rewrite

我想为所有网页维护一个网址,并且我使用index index.html指令在有人访问/writing/index.html时显示/writing/的网页。但是,使用此索引指令/writing/index.html仍然是nginx在。页面上提供页面的有效URL。

我希望/writing/index.html 301重定向到/writing/,依此类推根路径(/index.html - > /)和所有其他网址({{ 1}} - > /foo/bar/index.html)。

我想使用仅与/index.html结尾匹配的正则表达式,例如:/foo/bar/

但如果我添加

^(.*/)index\.html$

到我的nginx conf我看到 rewrite "^(.*)/index\.html$" $1 last; 301重定向到/writing/index.html这很好,但我也看到/writing/ 301在无限循环中重定向到/writing/

所以我的问题是为什么上面重写正则表达式匹配/writing/时它不会以/writing/结尾?是因为nginx conf中的内部索引指令吗?

我已经在StackOverflow上看到了其他一个用于重定向单个路径的解决方案,但没有像这样以干净/通用的方式执行此解决方案。

以下是我目前的nginx.conf

index.html

2 个答案:

答案 0 :(得分:1)

因此,解决此问题的方法是在一个位置内重写,以检查实际请求的$request_uri,这样可以避免使用index指令进行内部重新路由。

相当多地使用它:

if ($request_uri ~ "^(.*/)index\.html$") {
  rewrite "^(.*/)index\.html$" $1 permanent;
}

答案 1 :(得分:0)

我相信带有返回的位置块会更有效,更容易阅读:

location ~ ^(.*/)index\.html$ {
    return 301 $1;
}