A-A+

用nginx proxy_pass绕过跨域请求的问题

2017年07月17日 Linux 暂无评论 阅读 2,755 views 次

项目中,一些积分商城的东西,觉得放在app里太死,所以我们决定用web页面的形式嵌套在app里面,后端api的接口域名http://192.168.1.1:5000

现在web页面要调用该域,web页面的服务器我是通过nginx配置的8021端口,也就是说web域名为http://192.168.1.1:8021

当我在web页里向api发送ajax请求的时候会提示有跨域请求的问题。

如果是nginx + php ,从服务端配置允许跨域的http header头信息,在nginx和php里配置都可以:

1.在 nginx 里配置 add_header Access-Control-Allow-Origin "http://211.131.84.158:8021"

2.在 php 里配置 header("Access-Control-Allow-Origin:http://211.131.84.158:8021");

另一种方式通过 nginx 里的proxy_pass来配置。
server
{
listen       8021;
server_name  192.168.1.1 test.me;
index index.html;
root  /xxx/hujia;

location /request/ {
proxy_pass http://192.168.1.1:5000/;
proxy_redirect off;
proxy_set_header Host $host;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
}

access_log /xxx/test.access.log access_new;
}

这样后端哪些接口需要跨域也不用单独配置了。这样 web 页面请求自己当前域名下的request就被转发到内网的 http://192.168.1.1:5000/ 上去了。

需要注意不要出现if (!-e $request_filename)的判断了,否则进入不到上面我们配置的转发区间了。

标签:

给我留言

Copyright © 严佳冬 保留所有权利.   Theme  Ality 百度地图 苏ICP备19045515号-2

用户登录

分享到: