2016-08-02 28 views
0

我需要使用優庫https://github.com/openresty/lua-nginx-module如何傳遞給ngx_http_lua_module中的Nginx fastcgi_pass?

我更喜歡使用content_by_lua_block而不是set_by_lua_block到Nginx的變量傳遞給我的PHP 7.0的後端,因爲對於「設置」功能的文件指出「該指令被設計成執行短,由於Nginx事件循環在代碼執行期間被阻塞,所以快速運行的代碼塊應該避免,因此應該避免耗時的代碼序列。「 https://github.com/openresty/lua-nginx-module#set_by_lua

然而,由於「內容_...」功能是無阻塞的,下面的代碼沒有及時返回,並傳遞給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; 
} 

我的問題是,什麼是這裏最好的方法?只有在設置了變量後,纔有辦法從content_by_lua_block()中調用Nginx指令fastcgi_pass和相關指令?

回答

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 
     } 
    } 
+0

新的'default_type'在Nginx的conf就會從'應用程序/八位字節stream'更改爲'文本/ html,因爲我們使用ngx.say()來顯示PHP返回的HTML。 – AaronDanielson

相關問題