社区所有版块导航
Python
python开源   Django   Python   DjangoApp   pycharm  
DATA
docker   Elasticsearch  
aigc
aigc   chatgpt  
WEB开发
linux   MongoDB   Redis   DATABASE   NGINX   其他Web框架   web工具   zookeeper   tornado   NoSql   Bootstrap   js   peewee   Git   bottle   IE   MQ   Jquery  
机器学习
机器学习算法  
Python88.com
反馈   公告   社区推广  
产品
短视频  
印度
印度  
Py学习  »  NGINX

Nginx 跨域问题解决方案

MedusaSorcerer • 5 年前 • 591 次点击  
阅读 110

Nginx 跨域问题解决方案

MedusaSorcerer的博客


很多人都会遇到 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 的地址, 这样就可以达到解决跨域的问题。

Python社区是高质量的Python/Django开发社区
本文地址:http://www.python88.com/topic/70034
 
591 次点击