【问题标题】:NGINX rewrite/location regex redirect /index.html$ -> /NGINX 重写/位置正则表达式重定向 /index.html$ -> /
【发布时间】:2015-12-25 01:41:48
【问题描述】:

我想为所有页面维护一个 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/)。

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

但是如果我加了

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

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

所以我的问题是,为什么上面重写的正则表达式匹配/writing/,而它没有以index.html 结尾?是不是因为nginx conf里面的internal index指令?

我在 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/;
}

【问题讨论】:

  • 只是一个猜测......可能是 nginx 递归匹配它?这意味着 /write/ URL 不被正则表达式匹配,但是一旦它被重写到 /write/index.html 它匹配它并循环。
  • @Fawix 是的,我认为这样的事情正在发生。有一些内部重新路由,然后被index 指令捕获。关于如何防止这种情况发生的任何想法?

标签: regex redirect nginx rewrite


【解决方案1】:

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

几乎用这个代替:

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

【讨论】:

    【解决方案2】:

    我相信带有返回的位置块会更高效且更易于阅读:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-09-11
      • 2017-04-11
      相关资源
      最近更新 更多