Nginx 反向代理跨域问题解决

单域名

前端网站地址:http://xxxx.vip  
服务端代理网址:http://api.xxxx.vip
服务端地址:localhost:8085

server {
        listen       80;
        server_name  api.xxxx.vip;
        location  / {
          if ($request_method = 'OPTIONS') {
              add_header Access-Control-Allow-Origin 'http://xxxx.vip';
              add_header Access-Control-Allow-Headers 'Authorization,Content-Type,Accept,Origin,User-Agent,DNT,Cache-Control,X-Mx-ReqToken,X-Requested-With';
              add_header Access-Control-Allow-Methods 'GET,POST,OPTIONS';
              add_header Access-Control-Allow-Credentials 'true';
              # 允许客户端Js读到Content-Disposition 用于文件下载读取文件名
              add_header Access-Control-Expose-Headers 'Content-Disposition';
              return 204;
          }
          if ($request_method != 'OPTIONS') {
              add_header Access-Control-Allow-Origin 'http://xxxx.vip' always;
              add_header Access-Control-Allow-Credentials 'true';
          }
          proxy_pass  http://localhost:8085;
        }
}

 

或者

server {
        listen       80;
        server_name  api.xxxx.vip;
        location  / {
		  add_header Access-Control-Allow-Origin 'http://xxxx.vip' always;
		  add_header Access-Control-Allow-Headers 'Authorization,Content-Type,Accept,Origin,User-Agent,DNT,Cache-Control,X-Mx-ReqToken,X-Requested-With';
		  add_header Access-Control-Allow-Methods 'GET,POST,OPTIONS';
		  add_header Access-Control-Allow-Credentials 'true';
		  # 允许客户端Js读到Content-Disposition 用于文件下载读取文件名
		  add_header Access-Control-Expose-Headers 'Content-Disposition';
		  if ($request_method = 'OPTIONS') {
			  return 204;
		  }
		  proxy_pass  http://localhost:8085; 
        }
}

指定多个域名跨域配置

前端网站地址:http://xxxx.vip  http://xxxx.cc
服务端代理网址:http://api.xxxx.vip
服务端地址:localhost:8085

map $http_origin $allow_origin {
    default "";
    "~^(https?://localhost(:[0-9]+)?)" $1;
    "~^(https?://127.0.0.1(:[0-9]+)?)" $1;
    #"~^https://xxxx.vip" https://xxxx.vip;
    #"~^https://m.xxxx.vip" https://m.xxxx.vip;
    #"~^(https?://[\w]+.xxxx.vip)" $1;

    "~^(https?://([\w]+.)?[\w]+.xxxx.cc)" $1;
    "~^(https?://([\w]+.)?[\w]+.xxxx.vip)" $1;  #允许一级和二级域名
}

server {
        listen       80;
        server_name  api.xxxx.vip;
        location  / {
		  add_header Access-Control-Allow-Origin $allow_origin;
		  add_header Access-Control-Allow-Headers 'Authorization,Content-Type,Accept,Origin,User-Agent,DNT,Cache-Control,X-Mx-ReqToken,X-Requested-With';
		  add_header Access-Control-Allow-Methods 'GET,POST,OPTIONS';
		  add_header Access-Control-Allow-Credentials 'true';
		  # 允许客户端Js读到Content-Disposition 用于文件下载读取文件名
		  add_header Access-Control-Expose-Headers 'Content-Disposition';
		  if ($request_method = 'OPTIONS') {
			  return 204;
		  }
		  proxy_pass  http://localhost:8085; 
        }
}

 

posted @ 2022-07-23 15:55  Hexrui  阅读(560)  评论(0编辑  收藏  举报
返回顶部