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

Nginx variable names are lost between OpenResty captures

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

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

server {
    listen 1003;
    server_name ~^(?<name>test|acc)localhost$; #<-Name is set here

    location / {
        #return 200 $name; #This would return the expected test or 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; #<- Name is empty here
    }
}

有没有办法在不修改正文或使用 url 参数的情况下维护端点之间的变量?

您需要将选项添加到 ngx.location.capture 以共享或复制所有可用变量。

https://github.com/openresty/lua-nginx-module#ngxlocationcapture

copy_all_vars specify whether to copy over all the Nginx variable values of the current request to the subrequest in question. modifications of the nginx variables in the subrequest will not affect the current (parent) request. This option was first introduced in the v0.3.1rc31 release.

share_all_vars specify whether to share all the Nginx variables of the subrequest with the current (parent) request. modifications of the Nginx variables in the subrequest will affect the current (parent) request. Enabling this option may lead to hard-to-debug issues due to bad side-effects and is considered bad and harmful. Only enable this option when you completely know what you are doing.

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