网站首页 文章专栏 nginx 设置允许所有二级域名跨域Access-Control-Allow-Origin
nginx 设置允许所有二级域名跨域Access-Control-Allow-Origin
编辑时间:2021年6月21日 15:32 作者:赵彦昌 浏览量:3581

nginx 的 Access-Control-Allow-Origin 只允许是列表或* 并不能直接设置 *.test.com 域名

我们可以间接实现允许所有二级域名跨域 访问我们代理域名

关键nginx 配置片段如下:

location / {
                if ($http_origin ~* (htt(p|ps)?://.*\.zhaoyanchang\.com$)) {
                        add_header Access-Control-Allow-Origin  $http_origin;
                        add_header Access-Control-Allow-Credentials true;
                        add_header Access-Control-Allow-Methods 'GET, POST, 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';
                }

                        if ($request_method = 'OPTIONS') {
                                 return 204;
                        }


                proxy_pass http://myservice;
        }


当配置  路径  /   时,判断请求的 http_origin 是否http或https 开头并且是*.zhaoyanchang.com结尾。如果是则加上允许跨域的header


retrun 204 在跨域中是必须需要的

这样就达到了。我们允许所有二级域名跨哉访问的需求

来说两句吧
最新评论