Nginx跨域可统一在http块中配置:用map定义可信Origin白名单生成$cors_origin变量,配合add_header always设置CORS响应头,并在/api/ location中集中处理OPTIONS预检,实现全站复用与安全控制。

在 Nginx 中,跨域配置完全可以在 http 块中统一定义模板,避免每个 server 或 location 里重复写 add_header。关键是利用 map 指令做来源白名单映射,再结合 add_header 的继承性与条件触发逻辑,让所有需要跨域的接口自动复用同一套安全策略。
用 map 定义可信来源变量
在 http 块顶部(必须在任何 server 之前)添加:
map $http_origin $cors_origin {- default "";
- "~^https://(www\.)?example\.com$" $http_origin;
- "~^https://app\.example\.com$" $http_origin;
- "~^https://admin\.myapp\.net$" $http_origin;
- }
这个 map 把合法的 Origin 值原样赋给 $cors_origin 变量;不匹配的请求该变量为空,后续就不会加 CORS 头——既安全又免判断。
在 http 块中声明通用 CORS 响应头
继续在 http 块内(可放在 map 下方),定义一组带条件的响应头指令:
add_header 'Access-Control-Allow-Origin' $cors_origin 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 'Vary' 'Origin' always;
注意:必须加 always 标志,否则 Nginx 默认只对 2xx/3xx 响应生效,而 OPTIONS 预检返回的是 204,不加会失效。
在 location 中统一启用预检支持
不需要每个 server 单独写 if ($request_method = 'OPTIONS')。只需在公共 location 模板中集中处理,例如:
location /api/ {-
if ($cors_origin != "") { -
add_header 'Access-Control-Max-Age' '86400'; - }
-
if ($request_method = 'OPTIONS') { -
add_header 'Access-Control-Max-Age' '86400'; -
add_header 'Content-Length' 0; -
add_header 'Content-Type' 'text/plain; charset=utf-8'; -
return 204; - }
-
# 后续 proxy_pass 或 try_files 等实际逻辑 - }
这样只要所有 API 接口都走这个 /api/ 路径规则,就自动获得完整、合规的跨域能力,无需在每个 server 里复制粘贴。
补充:配合反向代理时的注意事项
如果用 proxy_pass 转发后端服务,还需确保:
- 后端响应头不覆盖 Nginx 添加的 CORS 头(可在
proxy_hide_header中屏蔽后端的同名头) - 转发请求时携带原始 Origin:
proxy_set_header Origin $http_origin; - 若后端需读取用户凭证(如 Cookie),必须同时设
proxy_pass_request_headers on;并确保前端credentials: 'include'
这种全局配置方式结构清晰、维护成本低,上线新域名或调整白名单只需改 map 一行,所有 server 自动同步生效。











