为什么这个 Nginx 配置会导致“重写或内部重定向循环”

aar*_*ron 4 nginx

我有以下 Nginx 配置:

server {
  listen   80;
  server_name  mercury;

  access_log  /var/log/nginx/mercury.access.log;
  error_log   /var/log/nginx/mercury.error.log;

  location /static {
    add_header Cache-Control: max-age=31536000;
  }

  location / {
    root   /opt/the-jam/www/dist/;
    try_files $uri /index.html;
    add_header Cache-Control: max-age=60;
  }
}
Run Code Online (Sandbox Code Playgroud)

我有目录结构:

§ tree /opt/the-jam/www/dist
/opt/the-jam/www/dist
??? index.html
??? static
    ??? 3522b60dabd4468d03f8.css
    ??? 3522b60dabd4468d03f8.js
Run Code Online (Sandbox Code Playgroud)

我收到错误:

2015/10/20 14:25:26 [error] 4529#0: *95 rewrite or internal redirection cycle while internally redirecting to "/index.html", client: 0.0.0.0, server: the-jam, request: "GET /favicon.ico HTTP/1.1", host: "the-jam.example.com", referrer: "http://the-jam.example.com/"
Run Code Online (Sandbox Code Playgroud)

这是一个单页应用程序,其中任何请求,即/foo/bar/baz应该只加载/index.html,除非它在 ​​中请求某些东西/static/[hash].js,所以我的理解是try_files指令将尝试在 加载文件/foo/bar/baz,然后回退到/index.html,那么为什么我会得到重定向循环?

Max*_*nin 9

您的配置的问题在于,如果/index.html找不到,它将重定向到/index.html. 最好避免这种配置,即使您确定文件在此处。像这样的配置没有这个问题:

root /opt/the-jam/www/dist/;

location / {
    try_files $uri /index.html;
    ...
}

location = /index.html {
    # no try_files here
    ...
}
Run Code Online (Sandbox Code Playgroud)

通过这样的配置,您还可以看到有什么问题/index.html以及为什么无法访问它。我最好的猜测是某些中间目录的访问权限不允许 nginx 访问/opt/the-jam/www/dist/index.html.