我们有一对夫妇的后端坐在我们的nginx前端后面。有没有可能拦截这些后端发送的301 / 302重定向,并让nginx处理它们?我们在想一些事情
error_page 302 = @target;
字符串但我怀疑301/302重定向可以处理相同的404等...我的意思是,错误页可能不适用于200等错误代码?所以总结一下:我们的后端偶尔会发回301/302。我们希望nginx截获这些,并将它们重写到另一个位置块,在那里我们可以用它们做任何其他事情。有可能吗?谢谢你,谢谢
iugsix8n1#
你可以使用proxy_redirect指令:http://nginx.org/en/docs/http/ngx_http_proxy_module.html#proxy_redirectNginx仍然会向客户端返回301/302,但是proxy_redirect会修改Location头,客户端应该向Location头中给出的URL发出新的请求。类似这样的东西应该会将后续的请求返回到nginx:proxy_redirect http://upstream:port/ http://$http_host/;个
proxy_redirect
Location
proxy_redirect http://upstream:port/ http://$http_host/;
eqoofvh92#
我成功地解决了一个更一般的情况,即重定向位置可以是任何外部URL。
server { ... location / { proxy_pass http://backend; # You may need to uncomment the following line if your redirects are relative, e.g. /foo/bar #proxy_redirect / /; 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; }}
server {
...
location / {
proxy_pass http://backend;
# You may need to uncomment the following line if your redirects are relative, e.g. /foo/bar
#proxy_redirect / /;
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;
字符串与您所描述的更接近的替代方法在ServerFault回答此问题时介绍:https://serverfault.com/questions/641070/nginx-302-redirect-resolve-internally
qfe3c7zg3#
如果您需要遵循多个重定向,请按如下所示修改Vlad的解决方案:1.添加
recursive_error_pages on;
字符串转换为location / .1.添加
location /
proxy_intercept_errors on; error_page 301 302 307 = @handle_redirects;
型到location @handle_redirects部分。
location @handle_redirects
44u64gxh4#
关于proxy_redirect的更多信息,用于相对位置
location /api/ { proxy_pass http://${API_HOST}:${API_PORT}/;}
location /api/ {
proxy_pass http://${API_HOST}:${API_PORT}/;
字符串
/api/
location /api/ { proxy_pass http://${API_HOST}:${API_PORT}/; proxy_redirect ~^/(.*) http://$http_host/api/$1;}
proxy_redirect ~^/(.*) http://$http_host/api/$1;
型
4条答案
按热度按时间iugsix8n1#
你可以使用
proxy_redirect
指令:http://nginx.org/en/docs/http/ngx_http_proxy_module.html#proxy_redirect
Nginx仍然会向客户端返回301/302,但是
proxy_redirect
会修改Location
头,客户端应该向Location
头中给出的URL发出新的请求。类似这样的东西应该会将后续的请求返回到nginx:
proxy_redirect http://upstream:port/ http://$http_host/;
个eqoofvh92#
我成功地解决了一个更一般的情况,即重定向位置可以是任何外部URL。
字符串
与您所描述的更接近的替代方法在ServerFault回答此问题时介绍:https://serverfault.com/questions/641070/nginx-302-redirect-resolve-internally
qfe3c7zg3#
如果您需要遵循多个重定向,请按如下所示修改Vlad的解决方案:
1.添加
字符串
转换为
location /
.1.添加
型
到
location @handle_redirects
部分。44u64gxh4#
关于
proxy_redirect
的更多信息,用于相对位置案例
字符串
/api/
前缀溶液
型