proxy模块的内容很多,我们暂时说一下最常用的 proxy_pass这个指令。
当我们遇到跨域问题,而且客户端无法支持 CORS 时,最好的办法就是让服务器来做代理。在前端页面所在的服务器 nginx 配置上开一个路由,然后使用 proxy 去请求另一个域名下的资源。如果跨域资源也部署在同一台机器上,我们甚至可以 proxy 到 127.0.0.1,比如:
1 2 3 | location /api { proxy_pass http://127.0.0.1:1234; } |
当客户端请求 /api 这个路径下的资源时服务器就会帮助我们去 127.0.0.1 的 1234 端口上取资源,解决了跨域的问题。proxy_pass 会将当前的 $uri 带过去,所以如果 /api 这个路由是我们擅自加的,在发送到目标服务前可以使用 rewrite 来处理掉这个多余的路由,比如:
1 2 3 4 | location /api/ { rewrite ^/api/(.*) /$1 break; proxy_pass http://127.0.0.1:1234; } |
rewrite 的作用是修改 $uri,但要注意 rewrite 要有个重新匹配 location 的副作用。由于 proxy_pass 的处理阶段比 location 处理更晚,所以这里需要 break 掉,以防止 rewrite 进入下一次 location 匹配而丢失 proxy_pass。$1表示第一个括号内匹配的正则参数。
在nginx中配置proxy_pass时,当在后面的url加上了/,相当于是绝对根路径,则nginx不会把location中匹配的路径部分代理走;如果没有/,则会把匹配的路径部分也给代理走。
1 2 3 4 5 6 7 8 9 10 11 | 若访问 http://nginx_server/test/index.html 1,若 location /test/ { proxy_pass http://192.168.1.1/ #有斜杠 } 则该请求被代理到 http://192.168.1.1/index.html 2,若 location /test/ { proxy_pass http://192.168.1.1 #没有斜杠 } 则该请求被代理到 http://192.168.1.1/test/index.html |