跨域问题(CORS)是前端开发中常见的问题,使用Nginx反向代理可以有效解决跨域问题。以下是Nginx配置跨域的基本方法:
server {
listen 80;
server_name your.domain.com;
location /api/ {
proxy_pass http://backend-server/; # 后端服务地址
# 核心跨域配置
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-Expose-Headers' 'Content-Length,Content-Range';
# 处理OPTIONS预检请求
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;
}
}
}
Access-Control-Allow-Origin:
*
表示允许所有域名访问add_header 'Access-Control-Allow-Origin' 'https://your-frontend.com';
Access-Control-Allow-Methods:
Access-Control-Allow-Headers:
OPTIONS预检请求处理:
# 限制允许的域名
map $http_origin $cors_origin {
default "";
"~^https://(example\.com|sub\.example\.com)$" $http_origin;
}
server {
# ...其他配置...
location /api/ {
# 使用变量控制允许的源
add_header 'Access-Control-Allow-Origin' $cors_origin;
add_header 'Access-Control-Allow-Credentials' 'true';
# ...其他配置...
}
}
多个域名需要跨域访问:
$http_origin
变量动态设置允许的源携带Cookie跨域:
Access-Control-Allow-Credentials: true
Access-Control-Allow-Origin
不能为*
,必须指定具体域名Nginx配置不生效:
http {
# 定义允许的跨域域名
map $http_origin $cors_origin {
default "";
"~^https://(www\.example\.com|api\.example\.com)$" $http_origin;
}
server {
listen 80;
server_name api.example.com;
location / {
# 反向代理到实际后端
proxy_pass http://localhost:8080;
# 跨域配置
if ($cors_origin) {
add_header 'Access-Control-Allow-Origin' $cors_origin;
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' 86400;
}
# 处理OPTIONS请求
if ($request_method = 'OPTIONS') {
return 204;
}
# 其他代理设置
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
}
}
}
通过以上配置,Nginx可以有效地处理跨域请求,同时保持一定的安全性。根据实际需求调整允许的域名、方法和头信息。