You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Nginx的proxy_pass中获取rewrite_by_lua块内更新的变量值

Nginx Lua变量更新后无法通过proxy_set_header传递的问题

定义了变量$myuser,在rewrite_by_lua_block里更新了它的值,想通过proxy_set_header把这个变量作为请求头传给后端,但后端拿到的始终是初始空值,不过在Lua块内部能正常获取到更新后的值。

原配置代码

location /
{
    set $myuser '';

    rewrite_by_lua_block
    {
        local user = -- 获取用户值的代码
        -- 错误时的重定向逻辑
        ngx.var.myuser = user
    }
  
    proxy_pass "https://backend.com";
    proxy_set_header myheader $myuser;
}

问题原因

这是Nginx配置指令执行顺序导致的:proxy_set_header在配置解析阶段就完成了变量值的静态替换,而rewrite_by_lua_block是在请求处理阶段才动态修改$myuser的值,所以proxy_set_header拿到的是变量初始化时的空值,而非Lua更新后的值。

解决方案

方案1:直接在Lua块中设置请求头

跳过Nginx变量中转,用ngx.req.set_header直接在Lua里设置请求头,确保后端拿到最新值:

location /
{
    rewrite_by_lua_block
    {
        local user = -- 获取用户值的代码
        -- 错误时的重定向逻辑
        ngx.req.set_header("myheader", user)
    }
  
    proxy_pass "https://backend.com";
}

方案2:用set_by_lua_block初始化变量(需保留$myuser时用)

如果必须保留$myuser变量供其他地方使用,可以用set_by_lua_block初始化变量,它的执行时机早于proxy_set_header的变量解析:

location /
{
    set_by_lua_block $myuser {
        local user = -- 获取用户值的代码
        return user
    }

    rewrite_by_lua_block
    {
        -- 错误时的重定向逻辑
        -- 此处可正常使用ngx.var.myuser
    }
  
    proxy_pass "https://backend.com";
    proxy_set_header myheader $myuser;
}

注意:set_by_lua_block只能做纯变量赋值,不能包含重定向、输出等副作用操作,重定向逻辑仍需放到rewrite_by_lua_block中执行。

内容的提问来源于stack exchange,提问作者lifetime_learner

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.02 19:26:14