0

我需要使用优秀的库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_...' 函数是非阻塞的,因此以下代码不会及时返回,并且 $hello 在传递给 PHP 时未设置:

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

我的问题是,这里最好的方法是什么?有没有办法fastcgi_pass在我的变量设置后才从 content_by_lua_block() 中调用 Nginx 指令和相关指令?

4

1 回答 1

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
        }
    }
于 2016-08-03T11:10:36.760 回答