map 中需注意,如果存在多个配置文件,不能使用相同的变量名,故这里示例为 $allow_origin_A
# 在 server 上方添加 map
map $http_origin $allow_origin_A {
default "";
"~^(https?://localhost(:[\d]+)?)" $1;
"~^(https?://127.0.0.1(:[\d]+)?)" $1;
"~^(https?://192.168.[\d]+.[\d]+(:[\d]+)?)" $1;
"~^(https?://front.example.com(:[\d]+)?)" $1;
}
server {
listen 80;
server_name api.example.com;
charset utf-8;
root /var/www/wwwroot/api.example.com;
add_header Access-Control-Allow-Origin $allow_origin_A;
add_header Access-Control-Allow-Credentials true;
add_header Access-Control-Expose-Headers 'HeaderA, HeaderB'; # 允许响应的头
location / {
# 用于强制跳转 HTTPS
#if ($scheme = http) {
# return 301 https://$host$request_uri;
#}
if ($request_method = 'OPTIONS') {
add_header Access-Control-Allow-Origin $allow_origin_A;
add_header Access-Control-Allow-Credentials true;
add_header Access-Control-Allow-Headers 'Accept, Authorization, Content-Type'; # 允许请求的头
add_header Content-Length 0;
return 204;
}
}
}
location ~ /\.ht {
deny all;
}
}