如何在ngx_http_lua_module中传递给Nginx fastcgi_pass?

时间:2016-08-02 01:03:30

标签: php nginx lua openresty ngx-core-module

我需要使用优秀的库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和相关指令?

1 个答案:

答案 0 :(得分:1)

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

    location /lua-subrequest-fastcgi {
        internal;   # this location block can only be seen by Nginx subrequests

        # Need to transform the %2F back into '/'.  Do this with set_unescape_uri()
        # Nginx appends '$arg_' to arguments passed to another location block.
        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."

            -- Send the URI from here (index.php) through the args list to the subrequest location.
            -- Pass it from here because the URI in that location will change to "/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
        }
    }