当浏览器发起ajax请求到其他域名时,会出现跨域的问题,在nginx上的解决方案是配置Access-Control-Allow-Origin来解决,此参数只允许配置单个域名或者*,当我们需要允许多个域名跨域访问时却不好配置,可以用map来实现
map $http_origin $corsHost {
default 0;
"~http://www.123admin.com" http://www.123admin.com;
"~http://m.123admin.com" http://m.123admin.com;
"~http://wap.123admin.com" http://wap.123admin.com;
}
server
{
listen 80;
server_name search.123admin.com;
root /nginx;
location /
{
add_header Access-Control-Allow-Origin $corsHost;
}
}
add_header Access-Control-Allow-Origin *;
location / {
if ($request_method = ‘OPTIONS‘) {
add_header Access-Control-Allow-Origin *;
add_header Access-Control-Allow-Methods ‘GET,POST,PUT,DELETE,OPTIONS‘;
add_header Access-Control-Allow-Headers ‘DNT,X-Mx-ReqToken,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Authorization‘;
add_header Access-Control-Allow-Credentials true;
return 204;
}
原文地址:https://www.cnblogs.com/mikeluwen/p/9528891.html
时间: 2024-10-17 04:06:29