插件窝 干货文章 Nginx如何实现基于响应头的请求重定向配置

Nginx如何实现基于响应头的请求重定向配置

location redirect proxy http 272    来源:    2025-04-10

Nginx 基于响应头的请求重定向配置

在 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;
    }
}

方法三:使用 Lua 模块(需要安装 ngx_http_lua_module)

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;
    }
}

注意事项

  1. 确保 Nginx 版本支持使用的指令
  2. 使用 proxy_redirect 时要小心正则表达式匹配
  3. 对于复杂逻辑,Lua 模块提供了最大的灵活性
  4. 测试时注意缓存问题,可使用 curl -v 查看完整响应头
  5. 重定向循环是需要特别注意避免的问题

以上方法可以根据实际需求选择使用,对于简单的重定向修改,proxy_redirect 通常是最简单直接的解决方案。