<p>关键是在 Nginx 层面拦截并返回 204 响应,而非转发 OPTIONS 请求;需用两个顺序明确的 location 块(OPTIONS 拦截在前)、add_header 加 always 参数、Origin 精确匹配且禁用 * 配合 credentials。</p>
要在 Nginx 的 location 块中正确支持特定跨域的 OPTIONS 预检请求,关键不是“允许”它转发给后端,而是由 Nginx 自己快速、合规地响应它。浏览器发来的预检请求(OPTIONS)不带请求体,也不需要业务逻辑,必须在 Nginx 层面拦截并返回 204 或 200 + 完整 CORS 头,否则会卡住或报错。
避免在 proxy_pass 同一个 location 内混用 if + proxy_pass——这会导致 header 丢失、502 错误或后端收不到真实请求头。
/api/)配置两个顺序明确的 location 块:第一个精准匹配 OPTIONS 请求,第二个处理真实转发if ($request_method = 'OPTIONS') {
add_header 'Access-Control-Allow-Origin' 'https://your-frontend.com' always;
add_header 'Access-Control-Allow-Methods' 'GET, POST, PUT, DELETE, OPTIONS' always;
add_header 'Access-Control-Allow-Headers' 'Content-Type, Authorization, X-Requested-With' always;
add_header 'Access-Control-Allow-Credentials' 'true' always;
add_header 'Access-Control-Max-Age' 1728000 always;
add_header 'Content-Length' 0;
add_header 'Content-Type' 'text/plain; charset=utf-8';
return 204;
}
}
location ^~ /api/ {
proxy_pass http://backend;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
}
add_header 默认只对 2xx 和 3xx 响应生效。而 OPTIONS 返回 204 是 2xx,看似没问题,但某些 Nginx 版本或嵌套上下文下仍可能失效。加上 always 可确保头字段稳定输出:
add_header Access-Control-Allow-Origin "https://your-frontend.com" always;add_header Access-Control-Allow-Credentials "true" always;always,带凭证(withCredentials: true)的请求大概率失败如果前端设置了 credentials: true(比如要传 Cookie),则 Access-Control-Allow-Origin 不能写 *,必须指定确切域名(支持多个域名需用 map 动态判断):
add_header Access-Control-Allow-Origin "https://app.example.com" always;
add_header Access-Control-Allow-Origin "*" always;(配合 credentials 会直接被浏览器拒绝)map 模块做白名单映射,再引用变量别只看浏览器控制台,要确认请求确实到达 Nginx 并得到合规响应:
$request_method $status 字段,复现请求后查日志是否有 OPTIONS 204
curl -X OPTIONS -H "Origin: https://app.example.com"
-H "Access-Control-Request-Method: POST"
-I http://your-api.com/api/user
检查响应头是否含 Access-Control-Allow-Origin 等字段,状态码是否为 204