Ngnix 配置允许多个域名跨域访问

当浏览器发起ajax请求到其他域名或者访问其他域名m3u8资源时,会出现跨域的问题,导致无法正确访问资源提示:

No'Access-Control-Allow-Origin' header is present on the requested resourse.Origin 'http//localhost:8088' is therefore not allowed access.

在nginx上的解决方案是配置Access-Control-Allow-Origin来解决,但是此参数只允许配置单个域名“add_header Access-Control-Allow-Origin baidu.com”或者“add_header Access-Control-Allow-Origin *;”允许全部域名,当我们需要允许多个域名跨域访问时却不好配置,可以用map来实现,具体代码如下:

 第一种方式:

map $http_origin $corsHost {
    default 0;
    "~http://www.haibakeji.com" http://www.haibakeji.com;
    "~http://m.haibakeji.com" http://m.haibakeji.com;
    "~http://wap.haibakeji.com" http://wap.haibakeji.com;
}

server
{
    listen 80;
    server_name www.haibakeji.com;
    root /nginx;
    location /
    {
        add_header Access-Control-Allow-Origin $corsHost;
    }
}

 原文网址:https://www.haibakeji.com/archives/249.html

第二种方式:

location ~* \.(ttf|ttc|otf|eot|woff|font.css)$ {

    if ($http_origin = 'http://backend.test.com') {

        add_header 'Access-Control-Allow-Origin' "$http_origin";

    }

    if ($http_origin = 'http://wap.test.com') {

        add_header 'Access-Control-Allow-Origin' "$http_origin";

    }

}

原文地址:https://www.jianshu.com/p/f2ec1d6af047

一个详细的说明网站:https://segmentfault.com/a/1190000003710973

posted @ 2018-09-10 17:03  刘小伟  阅读(4433)  评论(0编辑  收藏  举报