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

Nginx多源CORS配置异常:GET正常POST等请求失败求助

解决Nginx代理多源CORS下POST/PUT等请求失败的问题

核心问题在于非简单请求(POST/PUT/DELETE等)会先发送OPTIONS预检请求,原配置未单独处理这类请求,导致预检请求被转发到后端,而后端通常不处理OPTIONS方法,引发跨域失败。以下是修复方案:

步骤1:在Nginx的http块定义允许的源(用map替代if,更可靠)

map $http_origin $cors_allowed_origin {
    # 默认不允许任何源
    default "";
    # 替换成你需要允许的源,支持正则匹配多个域名(示例含主域名、子域名、带端口的域名)
    ~^https?://(domain1.com|sub.domain2.com|domain3:8080)$ $http_origin;
}

步骤2:修改cors.conf,添加OPTIONS请求处理

# 单独处理OPTIONS预检请求,直接返回204无需转发到后端
if ($request_method = OPTIONS) {
    add_header 'Access-Control-Allow-Origin' $cors_allowed_origin always;
    add_header 'Access-Control-Allow-Credentials' 'true' always;
    add_header 'Access-Control-Allow-Methods' 'GET, POST, PUT, DELETE, OPTIONS' always;
    add_header 'Access-Control-Allow-Headers' 'DNT,X-CustomHeader,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Authorization,username,x-auth-token' always;
    # 设置预检结果缓存时间,减少重复请求(单位:秒,示例为20天)
    add_header 'Access-Control-Max-Age' 1728000 always;
    add_header 'Content-Length' 0 always;
    add_header 'Content-Type' 'text/plain; charset=utf-8' always;
    return 204;
}

# 处理非OPTIONS请求的CORS响应头
if ($cors_allowed_origin != "") {
    add_header 'Access-Control-Allow-Origin' $cors_allowed_origin always;
    add_header 'Access-Control-Allow-Credentials' 'true' always;
    add_header 'Access-Control-Allow-Methods' 'GET, POST, PUT, DELETE, OPTIONS' always;
    add_header 'Access-Control-Allow-Headers' 'DNT,X-CustomHeader,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Authorization,username,x-auth-token' always;
}

步骤3:保持原server块的location配置不变

server {
    # ...其他配置...
    location /api/api1/ {
        proxy_pass http://api1/;
        include cors.conf;
    }
    # ...其他配置...
}

关键注意事项

  • 必须添加always参数:确保在非200状态码(比如404、500)的响应中,CORS头也能被正确添加。
  • 正则匹配要准确:map中的正则需覆盖所有需要允许的源,支持http/https协议、带端口的域名。
  • 无需转发OPTIONS请求:预检请求仅需Nginx返回正确头即可,转发到后端会导致不必要的错误。

内容的提问来源于stack exchange,提问作者Dimitar Daskalov

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.20 23:48:22