繁体   English   中英

NGINX重写/位置regex重定向/index.html$-> /

[英]NGINX rewrite/location regex redirect /index.html$ -> /

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

我希望/writing/index.html到301重定向到/writing/ ,对于根路径( /index.html > / )以及所有其他URL( /foo/bar/index.html > /foo/bar/ /foo/bar/index.html /foo/bar/ )。

我想使用仅匹配/index.html结尾的正则表达式,例如: ^(.*/)index\\.html$

但是如果我加上

  rewrite "^(.*)/index\.html$" $1 last;

到我的nginx conf上,我看到/writing/index.html 301重定向到/writing/ ,这很好,但是我也看到/writing/ /writing/index.html /writing/ 301在无限循环中重定向到/writing/

所以我的问题是,当上面的正则表达式未以index.html结尾时,为什么上面的正则表达式匹配/writing/ 是否由于nginx conf中的内部索引指令?

我已经在StackOverflow上看到了另一个解决方案,用于重定向单个路径,但是没有一种以这种干净/通用的方式实现此目的的解决方案。

以下是我当前的nginx.conf

server {
  listen         80;
  server_name example.com *.example.com;

  charset utf-8;

  gzip on;
  gzip_disable "msie6";

  gzip_vary on;
  gzip_proxied any;
  gzip_comp_level 6;
  gzip_buffers 16 8k;
  gzip_http_version 1.1;
  gzip_types text/plain text/css application/json application/x-javascript text/xml application/xml application/xml+rss text/javascript;

  rewrite "^(.*/)index\.html$" $1 permanent;

  location / {
    root /srv/www/example.com/;
    index index.html;
  }

  error_page 404 /404/;
}

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

几乎改用这个:

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

我相信附有回报的位置限制会更有效,也更容易阅读:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM