iprub互联网技术站

nginx 跨域设置

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

此时需要对 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 的地址, 这样就可以达到解决跨域的问题。

当前页面是本站的「Google AMP」版。查看和发表评论请点击:完整版 »

因本文不是用Markdown格式的编辑器书写的,转换的页面可能不符合AMP标准。