【问题标题】:Nginx try_files not working for default index.htmlNginx try_files 不适用于默认 index.html
【发布时间】:2018-07-15 01:42:57
【问题描述】:

我正在使用 nginx 的 $geoip_country_code 模块根据 IP 重定向用户。我的配置代码如下-

server {
      listen 80;
      gzip on;
      server_name example.com;
      root html/example;
      location / {
        index index.html;
        try_files /$geoip_country_code/index.html /index.html;
      }
      location ~* \.(gif|jpg|jpeg|png|js|css)$ { }
  }

想法是根据我已本地化的国家/地区重定向用户,否则用户将转到默认索引,即其他所有人的通用索引。当我在我的国家/地区的浏览器中打开它时,它可以完美运行,因为我已经对其进行了本地化。但是当从不同的国家打开时,它会显示内部服务器错误。它不会进入默认索引页面。

有人可以指出我做错了什么吗?

【问题讨论】:

  • 发布您在 nginx 访问/错误日志中看到的日志

标签: nginx devops nginx-location nginx-reverse-proxy


【解决方案1】:

try_files 语句的最后一个元素是默认操作,它可以是 URI 或响应代码。 /index.html 开始搜索新的 location 来处理请求,并在开始时返回,因此您有一个重定向循环。

您可以通过将/index.html 设为文件 术语来解决此问题。例如:

try_files /$geoip_country_code/index.html /index.html =404;

=404 永远不会被执行,因为/index.html 始终存在。

就个人而言,我会使用通用解决方案:

try_files /$geoip_country_code$uri $uri /index.html;

请参阅this document 了解更多信息。

【讨论】:

  • Nnginx 快把我逼疯了。当/index.html 明显存在时返回 404,并且在错误日志中不输出任何内容。您究竟是如何“将/index.html 改为file 术语”的? OP 已经有了try_files /$geoip_country_code/index.html /index.html;
  • @DanDascalescu 阅读链接文档。您将看到 try_files 接受一个或多个 file 参数,这些参数在同一 location 块中处理,但 last 参数是响应代码,名为 location或内部 URI。对于 URI,它看起来与文件术语相同,但会导致 Nginx 重新开始搜索匹配的location。 OP 的问题是 try_files 语句导致了重定向循环。
猜你喜欢
  • 1970-01-01
  • 2016-12-08
  • 1970-01-01
  • 1970-01-01
  • 2016-05-20
  • 1970-01-01
  • 2018-02-28
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多