Nginx 配置 https 和 配置 允许指定域名下所有二级域名跨域请求

如果网站 的地址 在 https://www.domain.xyz 上, 这个网站后端服务在 http:api.domain.xyz, 这样如果在 https:// www.domain.xyz 上
直接发送请求 到 http:api.domain.xyz 会出现跨域问题,因为虽然顶级域名相同,但是二级域名不同也会出现跨域(二级域名一个时 www,一个是 api)。

可采用如下 nginx 配置解决跨域问题:

nginx.conf 配置

nginx.conf

...

http {

    ...

    server {
        listen                  443 ssl;
        server_name             api.domain.xyz;
        # 配置 https
        #证书文件名称
        ssl_certificate         xxx.crt;
        #私钥文件名称
        ssl_certificate_key     xxx.key;

        # access_log  logs/api.domain.access.log;
        
        # 解决跨域问题
         set $flag '0';

         location / {
             # 将 api.domain.xyz 域名上的请求代理到 http://127.0.0.1:3000
             proxy_pass  http://127.0.0.1:3000;

             # 配置 domain.xyx 域名下的 所有 二级或多级域名 允许跨域请求
             if ($http_origin ~* "(https?://.*.domain.xyz($|/))") {
                  set $flag '1';
             }

             # 如果有 允许其它域名 进行跨域请求
             # if ($http_origin ~* "(https?://.*.otherdomain.xyz($|/))") {
             #    set $flag '1';
             # }

            if ($flag = '1') {
                 # 添加允许跨域的响应头
                 # add_header Access-Control-Allow-Origin "*";
                 add_header Access-Control-Allow-Origin "$http_origin";
                 ###带上用户认证信息
                 add_header Access-Control-Allow-Credentials  true;
                 ##允许的方法 post,get ...
                 add_header Access-Control-Allow-Methods  "POST, GET, PUT, PATCH, DELETE";
                 # add_header Access-Control-Allow-Headers "xxx-xx-xx";
            }
        }
    }
    
   ...
}


参考

nginx配置允许指定域名下所有二级域名跨域请求

原文地址:https://www.cnblogs.com/taohuaya/p/15417996.html