nginx 可以作为很好的反向代理工具,应用非常广泛,一般用来保护后方的服务器,避免直接被用户访问。
如果后方服务器返回 302,此时,如果不进行特殊处理,客户端也收到 302,但是如果客户端访问不到内部的服务器就要让 nginx 主动跟随 302 的地址,把内容取给我们,这需要进行如下设置:
server {
...
location /proxy {
proxy_pass http://127.0.0.1:8081;
proxy_intercept_errors on;
error_page 301 302 307 = @handle_redirects;
}
location @handle_redirects {
set $saved_redirect_location '$upstream_http_location';
proxy_pass $saved_redirect_location;
}
基本意思是添加对错误的处理,在服务器返回 302 302 307 的情况下,执行 handle_redirects 规则;
handle_redirects 规则中, set 设置变量 saved_redirect_location,然后再跳转过去。