如何在 ngx_http_lua_module 中快速传递到 Nginx 的 fastcgi_pass?

我需要使用优秀的库https://github.com/openresty/lua-nginx-module将一个Nginx变量传递给我的PHP 7.0后端。

我更喜欢使用“content_by_lua_block”而不是“set_by_lua_block”,因为“set”函数的文档说明:“此指令旨在执行短的,快速运行的代码块,因为Nginx事件循环在代码执行期间被阻塞。因此,应避免耗时的代码序列。”。 https://github.com/openresty/lua-nginx-module#set_by_lua

但是,由于“content_...”函数是非阻塞的,因此以下代码无法及时返回,并且在传递给PHP时未设置$hello:

location ~ \.php{
    set $hello '';

    content_by_lua_block {
        ngx.var.hello = "hello there.";
    }

    fastcgi_param HELLO $hello;
    include fastcgi_params;
    ...
    fastcgi_pass unix:/run/php/php7.0-fpm.sock;
}

问题是,如果采用某些代码路径,例如使用加密,我的Lua代码可能成为“耗时的代码序列”。

以下Nginx位置工作得很好,但这是因为set_by_lua_block()是一个阻塞函数调用:

location ~ \.php {
    set $hello '';

    set_by_lua_block $hello {
        return "hello there.";
    }

    fastcgi_param HELLO $hello;
    include fastcgi_params;
    ...
    fastcgi_pass unix:/run/php/php7.0-fpm.sock;
}

我的问题是,这里有最好的方法吗?是否有一种方法可以从content_by_lua_block()中调用Nginx指令“fastcgi_pass”和相关指令,仅在设置了我的变量后才能调用?

点赞
用户1504367
用户1504367

是的,使用ngx.location.capture是可行的。编写一个单独的location块,例如:

    location /lua-subrequest-fastcgi {
        internal;   #此location块只能被Nginx子请求看到

        #需要将%2F转换回'/'。使用set_unescape_uri()完成此操作
        #Nginx将'$arg_'附加到传递给另一个location块的参数。
        set_unescape_uri $r_uri $arg_r_uri;
        set_unescape_uri $r_hello $arg_hello;

        fastcgi_param HELLO $r_hello;

        try_files $r_uri =404;
        fastcgi_split_path_info ^(.+\.php)(/.+)$;
        include fastcgi_params;
        fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
        fastcgi_param SCRIPT_NAME $fastcgi_script_name;
        fastcgi_index index.php;
        fastcgi_pass unix:/run/php/php7.0-fpm.sock;
    }

然后可以将其调用:

    location ~ \.php {
        set $hello '';

        content_by_lua_block {
            ngx.var.hello = "hello, friend."

            --从这里(index.php)将URI从参数列表传递到子请求位置。
            --因为在该位置的URI将更改为“/lua-subrequest-fastcgi”,所以从这里传递。
            local res = ngx.location.capture ("/lua-subrequest-fastcgi", {args = {hello = ngx.var.hello, r_uri = ngx.var.uri}})

            if res.status == ngx.HTTP_OK then
                ngx.say(res.body)
            else
                ngx.say(res.status)
            end
        }
    }
2016-08-03 11:10:36