map 中需注意,如果存在多个配置文件,不能使用相同的变量名,故这里示例为 $allow_origin_A
1# 在 server 上方添加 map 2map $http_origin $allow_origin_A { 3 default ""; 4 "~^(https?://localhost(:[\d]+)?)" $1; 5 "~^(https?://127.0.0.1(:[\d]+)?)" $1; 6 "~^(https?://192.168.[\d]+.[\d]+(:[\d]+)?)" $1; 7 "~^(https?://front.example.com(:[\d]+)?)" $1; 8} 9 10server { 11 listen 80; 12 server_name api.example.com; 13 14 charset utf-8; 15 root /var/www/wwwroot/api.example.com; 16 17 add_header Access-Control-Allow-Origin $allow_origin_A; 18 add_header Access-Control-Allow-Credentials true; 19 add_header Access-Control-Expose-Headers 'HeaderA, HeaderB'; # 允许响应的头 20 21 location / { 22 # 用于强制跳转 HTTPS 23 #if ($scheme = http) { 24 # return 301 https://$host$request_uri; 25 #} 26 27 if ($request_method = 'OPTIONS') { 28 add_header Access-Control-Allow-Origin $allow_origin_A; 29 add_header Access-Control-Allow-Credentials true; 30 add_header Access-Control-Allow-Headers 'Accept, Authorization, Content-Type'; # 允许请求的头 31 32 add_header Content-Length 0; 33 return 204; 34 } 35 } 36 } 37 38 location ~ /\.ht { 39 deny all; 40 } 41}
