Nginx变量名在OpenResty捕获之间丢失

在Nginx中从server_name创建变量并使用ngx.location.capture调用不同的端点时,该变量就会消失。

以下示例通过调用testlocalhost和acclocalhost进行演示:

server {
    listen 1003;
    server_name ~^(?<name>test|acc)localhost$; #<-名称在此处设置

    location / {
        #返回预期的test或acc
        content_by_lua 'local options = {
                            method = ngx.HTTP_GET,
                        }
                        local res = ngx.location.capture("/internal", options)
                        ngx.say(res.body)';
    }

    location /internal {
        return 200 $name; #<- 名称在此为空
    }
}

是否有办法在不修改内容或使用URL参数的情况下在端点之间维护变量?

点赞
用户6257993
用户6257993

你需要添加选项到ngx.location.capture来共享或复制所有可用变量。https://github.com/openresty/lua-nginx-module#ngxlocationcapture

copy_all_vars 指定是否将当前请求中的所有Nginx变量值复制到所讨论的子请求中。在子请求中修改Nginx变量不会影响当前(父)请求。此选项首次在v0.3.1rc31发布中引入。

share_all_vars 指定是否与当前(父)请求共享字请求的所有Nginx变量。在子请求中修改Nginx变量会影响当前(父)请求。启用此选项可能会导致由于不良副作用而难以调试的问题,并被认为是不好和有害的。只有完全知道您在做什么时才启用此选项。

    location / {
        #return 200 $name; #This would return the expected test or acc
        content_by_lua '
            local options = {
                method = ngx.HTTP_GET,
                share_all_vars = true
            }
            local res = ngx.location.capture("/internal", options)
            ngx.say(res.body)'
        ;
    }
2017-09-27 17:24:06