跨域问题(CORS)是前端开发中常见的问题,当你的前端应用尝试访问不同域名、端口或协议的API时就会出现。以下是几种在Nginx中解决跨域问题的方法:
在Nginx配置文件中添加以下头部信息:
location / {
# 允许所有域名访问
add_header 'Access-Control-Allow-Origin' '*';
# 允许的请求方法
add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS, PUT, DELETE';
# 允许的请求头部
add_header 'Access-Control-Allow-Headers' 'DNT,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Range,Authorization';
# 预检请求缓存时间
add_header 'Access-Control-Max-Age' 1728000;
# 允许浏览器在跨域请求中携带凭证
# add_header 'Access-Control-Allow-Credentials' 'true';
# 响应类型
add_header 'Content-Type' 'text/plain; charset=utf-8';
# 响应长度
add_header 'Content-Length' 0;
# 对于OPTIONS请求直接返回204
if ($request_method = 'OPTIONS') {
return 204;
}
}
location / {
# 设置允许的域名,多个域名用空格分隔
set $cors '';
if ($http_origin ~* (https?://(www\.)?(example\.com|subdomain\.example\.com))) {
set $cors $http_origin;
}
add_header 'Access-Control-Allow-Origin' $cors;
add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS, PUT, DELETE';
add_header 'Access-Control-Allow-Headers' 'Content-Type, Authorization';
add_header 'Access-Control-Allow-Credentials' 'true';
if ($request_method = 'OPTIONS') {
return 204;
}
}
location /api/ {
add_header 'Access-Control-Allow-Origin' 'https://your-frontend-domain.com';
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,Range';
add_header 'Access-Control-Expose-Headers' 'Content-Length,Content-Range';
if ($request_method = 'OPTIONS') {
add_header 'Access-Control-Max-Age' 1728000;
add_header 'Content-Type' 'text/plain; charset=utf-8';
add_header 'Content-Length' 0;
return 204;
}
}
map $http_origin $cors_origin {
default "";
"~^https://([a-z0-9-]+\.)?example\.com$" $http_origin;
"~^http://localhost(:[0-9]+)?$" $http_origin;
}
server {
...
location / {
if ($cors_origin) {
add_header 'Access-Control-Allow-Origin' $cors_origin;
add_header 'Access-Control-Allow-Credentials' 'true';
add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS';
add_header 'Access-Control-Allow-Headers' 'Content-Type, Authorization';
}
if ($request_method = 'OPTIONS') {
return 204;
}
}
}
*
通配符时,不能与Access-Control-Allow-Credentials: true
同时使用*
nginx -s reload
可以使用curl命令测试:
curl -I -X OPTIONS http://your-domain.com/api/endpoint
检查返回的头部是否包含正确的CORS相关字段。
希望这些方案能帮助你解决Nginx跨域问题!根据你的具体需求选择合适的配置方式。