【问题标题】:Nginx : simple try_files with 301 return doesn't redirectNginx:返回 301 的简单 try_files 不会重定向
【发布时间】:2019-04-01 12:03:07
【问题描述】:

当本地找不到资源时,我想让 Nginx 重定向到外部 URL。这是我的配置:

server {
    listen       80;
    server_name  localhost;

    root   /usr/share/nginx/html;

    location / {
       try_files $uri @redirect;
       if ($request_method = 'GET') {
            add_header 'Access-Control-Allow-Origin' '*';
            add_header 'Access-Control-Allow-Credentials' 'true';
            add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS';
            add_header 'Access-Control-Allow-Headers' 'DNT,X-CustomHeader,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type';
        }
    }

    location @redirect {
        return 301 https://myfallbacksite.net$request_uri;
    }

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

当我尝试访问不存在的资源时,我只收到 404 并且请求不会重定向到备用网站。

我认为它以前有效,因此某处可能存在愚蠢的错字。 Nginx 错误日志说:

2018/10/28 10:22:35 [error] 9#9: *11 open() "/usr/share/nginx/html/picture.png" failed (2: No such file or directory), client: 172.19.0.1, server: localhost, request: "GET /picture.png HTTP/1.1", host: "myvhost", referrer: "https://www.originwebsite.com"

...这是真的(资源不存在),但我希望重定向请求而不是发回 404。

【问题讨论】:

  • 你好,检查 /usr/share/nginx/html 的权限是否改变了?如果没有,请尝试清除浏览器缓存并重试
  • @ben5556 感谢您的建议。由于即使尝试从该机器内部获取资源(执行 curl http://localhost/picture.png )我也会得到 404,所以它不可能是浏览器缓存问题。另外,如果是权限问题,我认为我会在错误日志中收到“权限被拒绝”错误,而不是“没有这样的文件或目录”
  • 我认为这可能是一个经典的"if is evil" 情况。
  • 是的,在进行快速测试时,删除 if 块会产生预期的结果。放回 if 块会导致 404。
  • @ben5556 和@Richard Smith 非常感谢!事实上,如果我离开 add_header 行但没有 if 包装它工作!如果你们中的一个人想在上面写一个答案,我会接受它:-)

标签: nginx redirect


【解决方案1】:

正如@ben5556 和@Richard Smith 所暗示的那样,if 声明是有原因的。 Nginx 文档实际上has a page 建议尽可能不要使用它。当我删除包裹在add_header 指令周围的if 时,一切都恢复了。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-02-27
    • 2013-01-01
    • 2021-08-04
    • 2020-10-29
    • 1970-01-01
    • 1970-01-01
    • 2015-07-21
    相关资源
    最近更新 更多