nginx跨域配置有三种生产级方法:一、在location中添加cors响应头并单独处理options预检;二、用反向代理使前后端同源;三、通过map模块实现动态origin白名单。

如果您在Linux系统中部署了Nginx作为Web服务器或反向代理,但前端页面调用后端API时遭遇浏览器拦截并提示CORS错误,则问题源于同源策略限制。以下是三种经生产环境验证的Nginx跨域配置方法:
一、在location块中直接添加CORS响应头
该方法适用于静态资源服务或简单API代理场景,通过add_header指令向所有匹配路径的响应注入标准CORS头部,使浏览器识别为合法跨域响应。
1、打开Nginx主配置文件,通常位于/etc/nginx/nginx.conf或站点配置文件如/etc/nginx/conf.d/default.conf。
2、在对应server块内的location /api/ { }中插入以下配置:
add_header 'Access-Control-Allow-Origin' 'https://your-frontend-domain.com';
add_header 'Access-Control-Allow-Methods' 'GET, POST, PUT, DELETE, OPTIONS';
add_header 'Access-Control-Allow-Headers' 'Content-Type, Authorization, X-Requested-With';
add_header 'Access-Control-Allow-Credentials' 'true';
add_header 'Access-Control-Expose-Headers' 'Content-Length, X-Request-ID';
3、特别处理预检请求:在同级location块中单独匹配OPTIONS方法,避免返回空体导致502错误:
if ($request_method = 'OPTIONS') { add_header 'Access-Control-Allow-Origin' 'https://your-frontend-domain.com'; add_header 'Access-Control-Allow-Methods' 'GET, POST, PUT, DELETE, OPTIONS'; add_header 'Access-Control-Allow-Headers' 'Content-Type, Authorization, X-Requested-With'; add_header 'Access-Control-Allow-Credentials' 'true'; add_header 'Access-Control-Max-Age' 1728000; add_header 'Content-Type' 'text/plain; charset=utf-8'; add_header 'Content-Length' 0; return 204; }
二、使用Nginx反向代理消除跨域根源
该方法不依赖CORS头部,而是让浏览器认为前后端同源:前端请求发往Nginx(如https://fe.example.com),Nginx将/api路径转发至后端服务(如http://127.0.0.1:8080/api),从而彻底规避同源策略校验。
1、确保Nginx已启用proxy模块,无需额外编译。
2、在server块中定义前端域名,并配置location /api/:
location /api/ { proxy_pass http://127.0.0.1:8080/; proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
proxy_redirect off;
proxy_buffering off;
}
3、重启Nginx服务:sudo systemctl restart nginx。
4、前端代码中所有API请求路径改为相对路径,例如从https://api.example.com/v1/user改为/api/v1/user。
三、基于map模块实现动态Origin白名单
该方法用于多前端域名共用同一套Nginx配置的场景,通过map指令将请求来源域名映射为允许的Origin值,既满足安全性要求,又避免硬编码多个add_header语句。
1、在http块顶部(server块外)添加map定义:
map $http_origin $cors_origin {
default "";
"https://fe1.example.com" "https://fe1.example.com";
"https://fe2.example.com" "https://fe2.example.com";
"https://staging-fe.example.com" "https://staging-fe.example.com";
}
2、在对应server块的location /api/中引用该变量:
add_header 'Access-Control-Allow-Origin' $cors_origin;
add_header 'Access-Control-Allow-Credentials' 'true';
add_header 'Access-Control-Allow-Methods' 'GET, POST, PUT, DELETE, OPTIONS';
add_header 'Access-Control-Allow-Headers' 'Content-Type, Authorization, X-Requested-With';
3、确保$http_origin变量在预检请求中可被正确捕获,必要时在server块中添加:
underscores_in_headers on;
4、测试时使用curl发送带Origin头的请求,验证响应头中Access-Control-Allow-Origin是否动态匹配。










