HttpLuaModule——翻譯(一)


最近經常使用春哥和小哲老師寫的NGINX-LUA,非常苦於沒有中文文檔,特別是向我這種英文水平實在有限的同學,所以將遇到的模塊記錄下來,供以后參考!原文:http://wiki.nginx.org/HttpLuaModule

lua_code_cache

一般放在nginx.conf里面,設置lua程序是否緩存,默認是開啟的,開發模式開啟即可:lua_code_cache off。開啟后,重啟nginx會有提示:nginx: [warn] lua_code_cache is off; this will hurt performance in /home/wb-liqiu/git/dante/conf/nginx.conf:30

lua_regex_cache_max_entries

lua_package_path

設置lua的包含路徑,例如:lua_package_path  '/home/wb-liqiu/git/dante/lib/?.lua;/home/lz/luax/?.lua;;';

lua_package_cpath

顧名思義,設置lua的C擴展的路徑,例如:lua_package_cpath '/home/lz/luax/?.so;;';

init_by_lua

設置lua的全局變量,在NGINX啟動的時候生效。例如:init_by_lua 'cjson = require "cjson"'; 事例:

init_by_lua 'cjson = require "cjson"';
 
    server {
        location = /api {
            content_by_lua '
                ngx.say(cjson.encode({dog = 5, cat = 6}))
            ';
        }
    }

 

還可以這么用:

 lua_shared_dict dogs 1m;
 
    init_by_lua '
        local dogs = ngx.shared.dogs;
        dogs:set("Tom", 56)
    ';
 
    server {
        location = /api {
            content_by_lua '
                local dogs = ngx.shared.dogs;
                ngx.say(dogs:get("Tom"))
            ';
        }
    }

init_by_lua_file

同上

set_by_lua

給nginx變量賦值

set_by_lua_file

content_by_lua

執行lua程序,例如:

    content_by_lua '
        ngx.print("test")
    ';

content_by_lua_file

同上

rewrite_by_lua

這個模塊經常在標准的HttpRewriteModule模塊之后執行。例如:

location /foo {
       set $a 12; # create and initialize $a
       set $b ""; # create and initialize $b
       rewrite_by_lua 'ngx.var.b = tonumber(ngx.var.a) + 1';
       echo "res = $b";
   }

 

執行之后,$b是13,當然如下語句就不能執行

  location /foo {
          set $a 12; # create and initialize $a
          set $b ''; # create and initialize $b
          rewrite_by_lua 'ngx.var.b = tonumber(ngx.var.a) + 1';
          if ($b = '13') {
             rewrite ^ /bar redirect;
             break;
          }
    
          echo "res = $b";
      }

ngx_eval 模塊類似於 rewrite_by_lua模塊。例如:

  location / {
        eval $res {
            proxy_pass http://foo.com/check-spam;
        }
 
        if ($res = 'spam') {
            rewrite ^ /terms-of-use.html redirect;
        }
 
        fastcgi_pass ...;
    }

 

 可以這么用:

 location = /check-spam {
        internal;
        proxy_pass http://foo.com/check-spam;
    }
 
    location / {
        rewrite_by_lua '
            local res = ngx.location.capture("/check-spam")
            if res.body == "spam" then
                return ngx.redirect("/terms-of-use.html")
            end
        ';
 
        fastcgi_pass ...;
    }

 

rewrite_by_lua在write模塊之后執行(除非rewrite_by_lua_no_postpone 設置為 on),例如:

 location /foo {
        rewrite ^ /bar;
        rewrite_by_lua 'ngx.exit(503)';
    }
    location /bar {
        ...
    }

rewrite_by_lua_file

同上

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM