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

同上

 

posted @ 2013-07-19 15:37  李秋  阅读(3523)  评论(0编辑  收藏  举报