跨域配置
单域名跨域
# 允许所有来源的跨域请求
add_header 'Access-Control-Allow-Origin' 'https://test.test.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,token,Authorization';
# 设置预检请求的有效期
add_header 'Access-Control-Max-Age' 1728000;
# 允许携带身份凭证(例如,cookie)
add_header 'Access-Control-Allow-Credentials' 'true';
# 处理预检请求(OPTIONS请求)
if ($request_method = 'OPTIONS') {
return 204;
}
多域名跨域
# 在http块中定义一个map,将请求的Origin映射到允许的Origin
map $http_origin $allowed_origin {
"~^(https://test1.test.com|https://test2.test.com|https://test3.test.com)$" $http_origin;
default "";
}
server {
listen 80;
listen 443 ssl http2;
server_name test.test.com;
index index.html index.htm index.php;
charset utf-8;
error_log /var/log/nginx/test.test.com-error.log error