Nginx try_files 不适用于默认的index.html

asy*_*oul 6 nginx devops nginx-location nginx-reverse-proxy

我正在使用 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)$ { }
  }
Run Code Online (Sandbox Code Playgroud)

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

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

Ric*_*ith 4

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

您可以通过创建文件/index.html术语来解决该问题。例如:

try_files /$geoip_country_code/index.html /index.html =404;
Run Code Online (Sandbox Code Playgroud)

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

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

try_files /$geoip_country_code$uri $uri /index.html;
Run Code Online (Sandbox Code Playgroud)

请参阅此文档了解更多信息。