You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Nginx反向代理Flask服务时POST请求返回405 Method Not Allowed问题

Nginx反向代理Flask后POST请求405错误的解决办法

问题根源

你的Nginx配置中添加了proxy_set_header Content-Type "application/json";,这行配置会强制覆盖客户端发送的请求头,导致Flask无法正确识别和处理POST请求,最终返回405 Method Not Allowed错误。

修复步骤

  1. 移除错误的请求头配置
    删除Nginx location块中的proxy_set_header Content-Type "application/json";这一行,让Nginx原样传递客户端的请求头给Flask服务。

  2. 修改后的完整Nginx配置

# nginx.conf
# HTTP server block for handling HTTP requests
server {
    listen 80;

    location / {
        proxy_pass http://flask:5000;
        proxy_http_version 1.1;
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
    }
}
  1. 验证修复效果
    重新加载Nginx配置:
    nginx -s reload
    
    再次执行之前的curl命令测试POST请求:
    curl -X POST -H "Content-Type: application/json" -d '{"message": "Hello from cURL!"}' http://x.x.x.x/
    
    此时应该能正常返回Flask服务的响应,不再出现405错误。

额外说明(可选)

如果你的服务需要处理跨域请求,可能会遇到OPTIONS预检请求被拦截的情况,可以在Nginx配置中添加以下规则,允许跨域:

location / {
    # 原有代理配置...
    
    # 处理OPTIONS预检请求
    if ($request_method = OPTIONS) {
        add_header Access-Control-Allow-Origin *;
        add_header Access-Control-Allow-Methods GET,POST,OPTIONS;
        add_header Access-Control-Allow-Headers Content-Type;
        return 204;
    }
}

内容的提问来源于stack exchange,提问作者James Mcgill

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.14 01:53:10