Nginx 中应使用 map 指令动态匹配白名单域名并赋值给 $cors_origin,再在 location 中通过 if 判断该变量非空时添加唯一 Access-Control-Allow-Origin 响应头,同时正确处理 OPTIONS 预检请求返回 204 状态码,以满足浏览器 CORS 规范要求。
在 Nginx 配置中允许特定域名跨域,关键不是直接写死多个 add_header,而是用 map 指令动态匹配来源,并只对白名单内的域名返回合法的 Access-Control-Allow-Origin 值——这是安全、合规且被浏览器接受的正确做法。
Nginx 的 map 块必须放在 http 全局上下文中(不能在 server 或 location 内),用于把请求头 $http_origin 映射为一个变量(如 $cors_origin),匹配成功则赋值为原来源,否则为空字符串:
在 http { ... } 块顶部添加:
map $http_origin $cors_origin {default "";"~^https?://(www.)?example.com$" $http_origin;"~^https?://app.mycompany.org$" $http_origin;"~^http://localhost:3000$" $http_origin;}
注意:正则需转义点号(.),支持 http/https,也兼容本地开发地址。
只要 $cors_origin 不为空,就代表来源合法,此时才注入响应头。同时必须处理 OPTIONS 预检请求:
location /api/)添加以下配置add_header 在 if 块内外都只对合法来源生效,避免对非法来源返回 * 或固定域名location /api/ {proxy_pass http://backend:8000;if ($cors_origin != "") {add_header 'Access-Control-Allow-Origin' $cors_origin;add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS, PUT, DELETE';add_header 'Access-Control-Allow-Headers' 'Content-Type, Authorization, X-Requested-With';add_header 'Access-Control-Expose-Headers' 'Content-Length, X-Total-Count';add_header 'Access-Control-Allow-Credentials' 'true'; # 如需带 cookie}if ($request_method = 'OPTIONS') {add_header 'Access-Control-Max-Age' 1728000;add_header 'Access-Control-Allow-Origin' $cors_origin;add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS, PUT, DELETE';add_header 'Access-Control-Allow-Headers' 'Content-Type, Authorization, X-Requested-With';add_header 'Access-Control-Allow-Credentials' 'true';return 204;}}
浏览器明确要求:Access-Control-Allow-Origin 只能是一个值或通配符 *,不能是逗号分隔列表。如果尝试硬编码多个域名(如 add_header Access-Control-Allow-Origin "a.com, b.com"),浏览器会直接拒绝该响应,报错 “The 'Access-Control-Allow-Origin' header contains multiple values”。所以必须靠 map + if 动态生成唯一合法值。
如果你启用了 Access-Control-Allow-Credentials: true(例如需要携带 Cookie 或 Authorization),那么 Access-Control-Allow-Origin 就绝对不能设为 *,必须精确匹配来源域名——这正是上面 map 方案的必要性所在。否则浏览器会静默拦截响应。