nginx.ccWeb 服务器排障台
405

Nginx 405 Not Allowed:POST 请求被拒绝的原因

快速答案

nginx 返回 405 Not Allowed,最常见的是 POST(或 PUT、DELETE)请求落到了静态文件上:静态文件只接受 GET 和 HEAD。通常是接口路径没有被 proxy_pass / fastcgi_pass 接走,被 try_files 回退到了 index.html。把接口 location 单独交给后端即可。

最常见的原因:SPA 的 try_files $uri /index.html 把 POST /api/... 也回退到了 index.html。

先这样改:接口单独交给后端

location /api/ {
    proxy_pass http://127.0.0.1:3000;
    proxy_set_header Host $host;
}
location / {
    try_files $uri $uri/ /index.html;
}

最后核对: · 依据下方列出的官方文档 · 出处

典型日志

"POST /api/login HTTP/1.1" 405 157
405 Not Allowed

常见原因

  1. SPA 的 try_files $uri /index.html 把 POST /api/... 也回退到了 index.html。
  2. 接口的 location 前缀写错(/api 和 /api/ 不一致),请求没进到 proxy_pass。
  3. 表单提交到 .html 静态页。
  4. 配置了 limit_except GET 等方法限制。

排查命令

看是 nginx 还是后端返回的 405
#curl -si -X POST https://example.com/api/login | head -5
请求会匹配到哪个 location
#nginx -T 2>/dev/null | grep -nE 'location|try_files|proxy_pass|limit_except'

修复配置

接口单独交给后端

location /api/ {
    proxy_pass http://127.0.0.1:3000;
    proxy_set_header Host $host;
}
location / {
    try_files $uri $uri/ /index.html;
}

改完先 nginx -t,通过后 systemctl reload nginx。

关键事实与出处

  • limit_except 限制 location 内允许的 HTTP 方法;允许 GET 时也会自动允许 HEAD。 [nginx.org]
  • error_page 指向 URI 时做内部重定向,并把 GET、HEAD 以外的请求方法改成 GET;指向命名 location(error_page 405 = @名字)则不改 URI 和方法。 [nginx.org]

以上事实于 2026-11-14 对照原文核对;nginx 版本更新后请以官方文档为准。

常见问题

能不能用 error_page 405 =200 $uri 绕过?

能让页面显示出来,但 POST 的数据被直接丢掉,接口并没有被调用。应该把请求交给真正处理它的后端。

怎么区分是 nginx 还是应用返回的 405?

nginx 的 405 页面底部有一行 nginx(或版本号),Server 头也是 nginx;应用的 405 通常带有 Allow 头和应用自己的错误格式。

用工具解决

相关报错

推广位(待接入)
这里以后会放 VPS / CDN 推荐,并标明「推广链接」。目前没有任何返佣链接。