【问题标题】:Nginx missing trailing slash returns 301Nginx 缺少斜杠返回 301
【发布时间】:2019-01-11 03:01:31
【问题描述】:

我有以下配置:

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。
  • @RichardSmith 我希望localhost:8000/applocalhost:8000/app 都指向同一个地方(index.html)
  • 重定向是由try_files语句中的$uri/引起的。你可以删除它。
  • @RichardSmith,你是不是建议只放try_files $uri /app/index.html?$args;?你能把它作为答案发布吗 - 它被排除在外

标签: nginx reverse-proxy


【解决方案1】:

try_files 语句中的 $uri/ 术语会导致 nginx 将尾随 / 附加到请求的 URI,如果该 URI 解析为本地目录。请参阅this document 了解更多信息。

通过发出 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;
}

【讨论】:

  • 它没有帮助。转到http://localhost:8000/app 后,我仍然被重定向到http://localhost/app/ - 仍然http://localhost:8000/app/ 按预期工作
  • 你重启了nginx,清除了浏览器缓存吗?
猜你喜欢
  • 1970-01-01
  • 2014-07-12
  • 2017-03-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-03-11
  • 1970-01-01
  • 2021-04-08
相关资源
最近更新 更多