跨域问题源于浏览器的同源策略(Same-Origin Policy),它限制了来自不同源(协议、域名、端口)的资源交互。CORS(Cross-Origin Resource Sharing)是一种W3C标准,允许服务器声明哪些外部源可以访问其资源。
server {
listen 80;
server_name example.com;
location / {
# 允许所有来源访问(生产环境应更严格)
add_header 'Access-Control-Allow-Origin' '*';
# 允许的HTTP方法
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';
# 预检请求(OPTIONS)结果缓存时间
add_header 'Access-Control-Max-Age' 1728000;
# 允许浏览器在跨域请求中暴露响应头
add_header 'Access-Control-Expose-Headers' 'Content-Length,Content-Range';
# 处理预检请求
if ($request_method = 'OPTIONS') {
return 204;
}
# 其他代理配置...
proxy_pass http://backend;
}
}
map $http_origin $cors_origin {
default "";
"~^https://(.*\.)?example\.com$" $http_origin;
"~^https://(.*\.)?trusted-site\.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-Credentials' 'true';
}
add_header 'Access-Control-Allow-Methods' 'GET, POST, PUT, DELETE, OPTIONS';
add_header 'Access-Control-Allow-Headers' 'Content-Type, Authorization';
if ($request_method = 'OPTIONS') {
return 204;
}
proxy_pass http://backend;
}
}
Access-Control-Allow-Origin
*
允许所有域访问(不推荐生产环境使用)https://example.com
)Access-Control-Allow-Methods
Access-Control-Allow-Headers
Access-Control-Allow-Credentials
true
时允许发送凭据(cookies等)Access-Control-Max-Age
OPTIONS请求处理
现象: 浏览器发送OPTIONS请求但返回404或405
解决: 确保Nginx正确处理OPTIONS方法:
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' 'Authorization,Content-Type';
add_header 'Access-Control-Max-Age' 1728000;
add_header 'Content-Type' 'text/plain; charset=utf-8';
add_header 'Content-Length' 0;
return 204;
}
现象: 使用withCredentials但请求失败
解决: 需要明确指定允许的来源(不能使用*)并启用凭据:
add_header 'Access-Control-Allow-Origin' 'https://client.example.com';
add_header 'Access-Control-Allow-Credentials' 'true';
现象: 自定义头如Authorization被拦截
解决: 在Allow-Headers中明确列出:
add_header 'Access-Control-Allow-Headers' 'Authorization, X-Custom-Header, Content-Type';
*
作为允许的来源可以使用curl命令测试:
# 测试简单请求
curl -I -X GET https://api.example.com/resource -H "Origin: https://client.example.com"
# 测试预检请求
curl -I -X OPTIONS https://api.example.com/resource \
-H "Origin: https://client.example.com" \
-H "Access-Control-Request-Method: POST" \
-H "Access-Control-Request-Headers: Content-Type,Authorization"
通过合理配置Nginx的CORS支持,可以安全地实现跨域资源访问,同时保护API免受恶意利用。