【问题标题】:nginx return 405 Not Allowed while using try_files and proxy_passnginx 在使用 try_files 和 proxy_pass 时返回 405 Not Allowed
【发布时间】:2020-01-20 00:36:25
【问题描述】:

我想使用 nginx 来提供一些静态文件并将 restful api 反向代理到后端。 我使用 docker 将它们全部包装起来。

以下是我的配置文件/etc/nginx/conf.d/default.conf

server {
    listen 80;
    # gzip config
    gzip on;
    gzip_min_length 1k;
    gzip_comp_level 9;
    gzip_types text/plain text/css text/javascript application/json application/javascript application/x-javascript application/xml;
    gzip_vary on;
    gzip_disable "MSIE [1-6]\.";

    root /usr/share/nginx/html;

    location / {
        try_files $uri $uri/ /index.html @backend;
        error_page 405 @backend;
    }

    location /terminal {
        proxy_pass http://dns-management-backend:8080;
        proxy_http_version 1.1;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection "upgrade";
        proxy_set_header   X-Forwarded-Proto $scheme;
        proxy_set_header   X-Real-IP         $remote_addr;
    }

    location @backend {
        proxy_pass http://dns-management-backend:8080;
        proxy_set_header   X-Forwarded-Proto $scheme;
        proxy_set_header   X-Real-IP         $remote_addr;
    }
}

静态文件正常,但 restful api 用405 Not Allowed返回给我。

这里是nginx的日志

192.168.16.2 - - [19/Sep/2019:02:59:38 +0000] "POST /sys/login HTTP/1.1" 405 796 "http://dns-management.api.my.domain/" "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/77.0.3865.75 Safari/537.36" "113.55.15.1"

【问题讨论】:

  • 如果您想从 405 更改错误代码,请尝试:error_page 405 = @backend;
  • @RichardSmith,感谢您的建议。但是我找到了根本原因,请参阅下面的答案。

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


【解决方案1】:

终于找到原因了,是try_files指令的错误使用,如果请求的url是POST /sys/login,那么POST /index.html就被服务了。所以出现了 405 Not Allowed。

解决方法很简单,将try_files 指令更改为try_files $uri $uri/index.html @backend;

【讨论】:

    猜你喜欢
    • 2014-04-09
    • 1970-01-01
    • 2023-03-08
    • 2011-09-25
    • 2016-02-23
    • 1970-01-01
    • 2020-09-22
    • 2021-06-14
    • 2016-12-04
    相关资源
    最近更新 更多