Nginx缺少尾斜杠会返回301状态码。

4

I have the following config:

server {
  listen       80;
  server_name  localhost;

  location  /app {
    root   /usr/share/nginx/html;
    index  index.html index.htm;
    try_files $uri $uri/ /app/index.html?$args;
  }

  error_page   500 502 503 504  /50x.html;
  location = /50x.html {
    root   /usr/share/nginx/html;
  }
}

当访问http://localhost:8000/app/时,一切都按预期进行,但是当去掉尾部斜杠(http://localhost:8000/app)时,nginx返回301状态响应并将我重定向到http://localhost/app
我如何让nginx同时处理带和不带尾部斜杠的http://localhost:8000/app/http://localhost:8000/app

当一个没有尾随斜杠的URI指向一个目录时,您希望nginx做什么?目前,$uri/告诉它发出3xx响应,而listen指令告诉它在重定向中使用端口80。 - Richard Smith
@RichardSmith 我想让 http://localhost:8000/app/ 和 http://localhost:8000/app 指向同一个位置(即 index.html)。 - vlio20
重定向是由try_files语句中的$uri/引起的。你可以将其删除。 - Richard Smith
@RichardSmith,您是在建议只放置 try_files $uri /app/index.html?$args; 吗?您能将其发布为答案-以便被接受。 - vlio20
2个回答

7
$uri/try_files语句中的作用是,如果请求的URI解析为本地目录,则导致nginx在其末尾附加一个斜杠/。有关更多信息,请参见此文档
通过发出3xx响应来追加斜杠/,当然nginx凭借其对8000端口一无所知而获得错误的端口。
如果您不希望nginx发出任何3xx响应,请从您的try_files语句中删除$uri/项。
例如:
location  /app {
    root   /usr/share/nginx/html;
    index  index.html index.htm;
    try_files $uri /app/index.html?$args;
}

1
没有帮助。在访问http://localhost:8000/app后,我仍然被重定向到http://localhost/app/ - http://localhost:8000/app/仍然按预期工作。 - vlio20
1
你重启了nginx吗?并且清除了浏览器缓存吗? - Richard Smith

0

你只需要这个:

 port_in_redirect on;

但是如果你希望你的服务器对公众开放,请注意转发端口。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接