在 Nginx 中配置跨域(CORS)可以通过添加特定的 HTTP 头部来实现。以下是完整的跨域配置解决方案:
server {
listen 80;
server_name example.com;
location / {
# 允许所有域名跨域访问
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,Range,Authorization';
# 预检请求缓存时间
add_header 'Access-Control-Max-Age' 1728000;
# 允许浏览器在跨域请求中携带凭证(如cookies)
# add_header 'Access-Control-Allow-Credentials' 'true';
# 其他正常配置...
proxy_pass http://backend;
}
}
map $http_origin $cors_origin {
default "";
"~^https://example.com$" $http_origin;
"~^https://sub.example.com$" $http_origin;
}
server {
listen 80;
server_name api.example.com;
location / {
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';
add_header 'Access-Control-Allow-Credentials' 'true';
add_header 'Access-Control-Max-Age' 1728000;
}
# 处理OPTIONS预检请求
if ($request_method = 'OPTIONS') {
return 204;
}
# 其他正常配置...
proxy_pass http://backend;
}
}
server {
listen 80;
server_name api.example.com;
location /api/ {
add_header 'Access-Control-Allow-Origin' 'https://example.com';
add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS';
add_header 'Access-Control-Allow-Headers' 'Content-Type, Authorization';
if ($request_method = 'OPTIONS') {
return 204;
}
proxy_pass http://backend;
}
# 其他location配置...
}
Access-Control-Allow-Credentials
设置为 true
时,Access-Control-Allow-Origin
不能使用通配符 *
,必须指定具体域名*
通配符,而是明确指定允许的域名nginx -s reload
可以使用以下curl命令验证配置是否生效:
curl -I -X OPTIONS http://api.example.com/api/endpoint -H "Origin: https://example.com"
应该能看到返回的CORS相关头部信息。
以上配置可以根据实际需求进行调整,确保安全性和功能性的平衡。