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