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


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM