这里说明下:http://www.nginx.com:8081是nginx的ip地址和端口 而test则是真正的后端接口地址,假设后端的完整接口地址是“www.server.com:8080/test” 那么nginx在配置完转发规则后再请求"http://www.nginx.com:8081/cross/test"的时候,由于已经配置的转发,所以相当于就是请求“www.server.com:8080/test” 也不会造成跨域。
nginx配置部分:
location /cross/ {
proxy_pass http://www.server.com:8080/;
}
这里说明下:"/cross/" 这个东西是前端请求时候需要带上的
"http://www.server.com:8080/"是后端地址和端口(不要忘了后面的 “/” )
而在前端ajax请求时:
$.ajax({
url: "http://www.nginx.com:8081/cross/test",
type: "get",
})
注:这种情况下前端文件只能放在nginx的目录下,如果要把文件和nginx分开放的话,也会出现跨域的情况,那么要解决这个问题的话需要加上
location /cross/ {
add_header Access-Control-Allow-Origin *;
add_header Access-Control-Allow-Methods 'GET, POST, OPTIONS';
add_header Access-Control-Allow-Headers 'DNT,X-Mx-ReqToken,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Authorization,cookietoken,cookieuid,lang';
if ($request_method = 'OPTIONS') {
return 200;
}
proxy_pass http://www.server.com:8080/;
}