在 Nginx 中,可以通过多种方式实现基于响应头的重定向。以下是几种常见的方法:
map
指令和 $upstream_http_*
变量http {
map $upstream_http_location $redirect_url {
default "";
~^(https?://[^/]+)(.*) $1/newpath$2;
}
server {
location / {
proxy_pass http://backend;
if ($redirect_url) {
return 301 $redirect_url;
}
}
}
}
proxy_redirect
指令server {
location / {
proxy_pass http://backend;
proxy_redirect ~^(https?://[^/]+)(.*) $1/newpath$2;
}
}
server {
location / {
proxy_pass http://backend;
header_filter_by_lua '
local location = ngx.header.location
if location then
ngx.header.location = string.gsub(location, "^(https?://[^/]+)(.*)", "%1/newpath%2")
end
';
}
}
server {
location / {
proxy_pass http://backend;
proxy_intercept_errors on;
error_page 301 302 307 = @handle_redirect;
}
location @handle_redirect {
if ($upstream_http_location ~* "^https?://example.com/oldpath(.*)") {
return 301 https://example.com/newpath$1;
}
proxy_pass $upstream_http_location;
}
}
proxy_redirect
时要小心正则表达式匹配curl -v
查看完整响应头以上方法可以根据实际需求选择使用,对于简单的重定向修改,proxy_redirect
通常是最简单直接的解决方案。