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

最新下载

热门教程

Nginx 配置文件中如何配置跨域资源共享 CORS 允许特定域名

时间:2026-08-20 11:59:48 编辑:袖梨 来源:一聚教程网

Nginx 中应使用 map 指令动态匹配白名单域名并赋值给 $cors_origin,再在 location 中通过 if 判断该变量非空时添加唯一 Access-Control-Allow-Origin 响应头,同时正确处理 OPTIONS 预检请求返回 204 状态码,以满足浏览器 CORS 规范要求。

在 Nginx 配置中允许特定域名跨域,关键不是直接写死多个 add_header,而是用 map 指令动态匹配来源,并只对白名单内的域名返回合法的 Access-Control-Allow-Origin 值——这是安全、合规且被浏览器接受的正确做法。

用 map 指令定义可信来源

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,也兼容本地开发地址。

在 location 中有条件添加 CORS 头

只要 $cors_origin 不为空,就代表来源合法,此时才注入响应头。同时必须处理 OPTIONS 预检请求:

  1. 在对应 location 块内(比如 location /api/)添加以下配置
  2. 确保 add_headerif 块内外都只对合法来源生效,避免对非法来源返回 * 或固定域名
  3. 预检请求(OPTIONS)必须返回 204 状态码,且不转发给后端
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;}

}

为什么不能直接写多个 add_header?

浏览器明确要求: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 动态生成唯一合法值。

额外提醒:Credentials 与 Origin 不能共存于 *

如果你启用了 Access-Control-Allow-Credentials: true(例如需要携带 Cookie 或 Authorization),那么 Access-Control-Allow-Origin 就绝对不能设为 *,必须精确匹配来源域名——这正是上面 map 方案的必要性所在。否则浏览器会静默拦截响应。

热门栏目