Nginx跨域配置必须加在server或location块内,禁用*响应凭证需指定域名,预检请求需单独处理OPTIONS并返回204,还需排除CDN与缓存干扰。

直接加 add_header 就能生效?别急,先看位置对不对
加跨域头不是往配置文件随便一贴就完事。宝塔里必须加在网站的 Nginx 配置「server 块内」,且最好在 location / 或具体接口路径的 location 块里——如果加在 http 或 upstream 块,Nginx 启动会报错或不生效。
- 正确位置示例:
server { ... location /api/ { add_header 'Access-Control-Allow-Origin' '*'; } } - 静态资源单独放行?用正则匹配后缀:
location ~* \.(js|css|png|jpg)$ { add_header 'Access-Control-Allow-Origin' '*'; } - 改完必须点「保存」+「重启 Nginx」,只重载(reload)有时不刷新 header
带 Cookie 的请求为什么被拒?Access-Control-Allow-Credentials 不能配 *
前端用了 fetch(..., { credentials: 'include' }) 或 axios.defaults.withCredentials = true,但响应里 Access-Control-Allow-Origin: * 会导致浏览器直接拦截——这是规范强制要求。
- 必须指定具体域名:
add_header 'Access-Control-Allow-Origin' 'https://your-frontend.com'; - 同时开启凭证支持:
add_header 'Access-Control-Allow-Credentials' 'true'; - 注意:如果前端是
http://localhost:8080,这里也得写成http://localhost:8080,协议、端口、域名缺一不可
预检请求(OPTIONS)失败?漏了方法和头声明
当请求含自定义 header(如 Authorization)或非简单方法(PUT/DELETE),浏览器会先发 OPTIONS 请求。如果 Nginx 没返回允许的响应,后续请求根本不会发出。
- 补全必要 header:
add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS, PUT, DELETE'; - 允许自定义 header:
add_header 'Access-Control-Allow-Headers' 'DNT,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Authorization'; - 让 OPTIONS 直接返回 204:
if ($request_method = 'OPTIONS') { add_header 'Access-Control-Allow-Origin' '*'; add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS'; add_header 'Access-Control-Allow-Headers' 'DNT,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Authorization'; add_header 'Access-Control-Max-Age' 1728000; add_header 'Content-Type' 'text/plain; charset=utf-8'; add_header 'Content-Length' 0; return 204; }
配置明明写了却没看到 header?先排除缓存和 CDN 干扰
浏览器 DevTools 的 Network 面板看不到 Access-Control-Allow-Origin,不一定是配置错了,很可能是中间环节把 header 给吞了。
- 浏览器强刷(
Ctrl+Shift+R)或禁用缓存再试 - 如果用了 CDN(如腾讯云 CDN、Cloudflare),它们默认不透传自定义 header,需在 CDN 控制台开启「允许跨域响应头透传」或手动添加响应头规则
- 检查 Nginx 错误日志:
/www/wwwlogs/nginx_error.log,常见错误如语法错误、重复 header、权限不足导致证书读取失败(尤其配了 HTTPS 后)
Nginx 跨域配置真正卡住人的地方,往往不是加哪几行,而是哪几层在“过滤”你加的 header——浏览器、CDN、反向代理、甚至 SSL 重定向链路都可能悄悄吃掉它。每次改完,务必用 curl -I <a href="https://www.php.cn/link/054dc98b329e8837d6429c4840c88268">https://www.php.cn/link/054dc98b329e8837d6429c4840c88268</a> 直连服务器验证原始响应头。










