一聚教程网:一个值得你收藏的教程网站

最新下载

热门教程

Nginx location 配置中如何配置以允许特定的跨域 OPTIONS 预检

时间:2026-08-18 19:48:48 编辑:袖梨 来源:一聚教程网

<p>关键是在 Nginx 层面拦截并返回 204 响应,而非转发 OPTIONS 请求;需用两个顺序明确的 location 块(OPTIONS 拦截在前)、add_header 加 always 参数、Origin 精确匹配且禁用 * 配合 credentials。</p>

要在 Nginx 的 location 块中正确支持特定跨域的 OPTIONS 预检请求,关键不是“允许”它转发给后端,而是由 Nginx 自己快速、合规地响应它。浏览器发来的预检请求(OPTIONS)不带请求体,也不需要业务逻辑,必须在 Nginx 层面拦截并返回 204 或 200 + 完整 CORS 头,否则会卡住或报错。

用独立 location 拦截 OPTIONS(推荐)

避免在 proxy_pass 同一个 location 内混用 if + proxy_pass——这会导致 header 丢失、502 错误或后端收不到真实请求头。

  1. 为 API 路径(如 /api/)配置两个顺序明确的 location 块:第一个精准匹配 OPTIONS 请求,第二个处理真实转发
  2. OPTIONS location 必须写在 proxy_pass location 之前,否则 Nginx 可能按字典序误匹配
  3. 示例配置:
location ^~ /api/ {

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;

}

必须加 always 参数

add_header 默认只对 2xx 和 3xx 响应生效。而 OPTIONS 返回 204 是 2xx,看似没问题,但某些 Nginx 版本或嵌套上下文下仍可能失效。加上 always 可确保头字段稳定输出:

  1. add_header Access-Control-Allow-Origin "https://your-frontend.com" always;
  2. add_header Access-Control-Allow-Credentials "true" always;
  3. 没有 always,带凭证(withCredentials: true)的请求大概率失败

Origin 必须精确匹配,不能用 * 配合 credentials

如果前端设置了 credentials: true(比如要传 Cookie),则 Access-Control-Allow-Origin 不能写 *,必须指定确切域名(支持多个域名需用 map 动态判断):

  1. ✅ 正确:add_header Access-Control-Allow-Origin "https://app.example.com" always;
  2. ❌ 错误:add_header Access-Control-Allow-Origin "*" always;(配合 credentials 会直接被浏览器拒绝)
  3. 若需多域名,可用 map 模块做白名单映射,再引用变量

验证预检是否真正生效

别只看浏览器控制台,要确认请求确实到达 Nginx 并得到合规响应:

  1. 在 access_log 中添加 $request_method $status 字段,复现请求后查日志是否有 OPTIONS 204
  2. 用 curl 模拟预检:

    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

热门栏目