关于nginx:Nginx-跨域问题解决方案

1次阅读

共计 1121 个字符,预计需要花费 3 分钟才能阅读完成。

很多人都会遇到 Nginx 跨域的问题, 而我遇到的问题是:

  • 客户端在 www.a.com
  • 服务端在 www.b.com
  • Nginx 在 www.c.com

此时须要对 Nginx 进行跨域配置才能够拜访 www.c.com 的获取客户端 www.a.com 来申请 www.b.com 的数据, 我的 Nginx 配置如下 (重要局部):

location / {
    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,web-token,app-token,Authorization,Accept,Origin,Keep-Alive,User-Agent,X-Mx-ReqToken,X-Data-Type,X-Auth-Token,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Range';
    add_header 'Access-Control-Expose-Headers' 'Content-Length,Content-Range';
    if ($request_method = 'OPTIONS') {
            add_header 'Access-Control-Max-Age' 1728000;
            add_header 'Content-Type' 'text/plain; charset=utf-8';
            add_header 'Content-Length' 0;
            return 204;
    }
    root   html;
    proxy_pass http://xxx:8000/;
    proxy_set_header Host $host;
    proxy_set_header X-Real-IP $remote_addr;
    proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
    proxy_set_header X-Forwarded-Proto $scheme;
    proxy_connect_timeout 5;
}

别忘了把配置中 proxy_pass 对应的 http://xxx:8000/ 地址换成你的服务地址, 当然了, 你的客户端申请的地址不能够是你的服务地址, 而是 Nginx 的地址, 这样就能够达到解决跨域的问题。感兴趣的敌人能够在 3A 服务器部署一套本人试验下。

正文完
 0