nginx-lua集中管理.md 2.62 KB

nginx-lua模块集中化管理

安装

安装luajit 下载nginx、ngx_devel_kit-0.3.0、lua-nginx-module-0.10.6

  • luajit
wget -c http://luajit.org/download/LuaJIT-2.0.2.tar.gz
tar xzvf LuaJIT-2.0.2.tar.gz
cd LuaJIT-2.0.2
make install
  • nginx编译
wget 'http://nginx.org/download/nginx-1.11.2.tar.gz'
tar -xzvf nginx-1.11.2.tar.gz
cd nginx-1.11.2/
export LUAJIT_LIB=/path/to/luajit/lib
export LUAJIT_INC=/path/to/luajit/include/luajit-2.0
./configure --add-module=/path/to/ngx_devel_kit --add-module=/path/to/lua-nginx-module
make
make install

配置

  • nginx代码实例

    location / {
    set $pass "127.0.0.1:6001";
    set $cache 0;
    set $fenxiLog 0;
    access_by_lua_file /usr/local/nginx/lua_modules/lua_router.lua;
    }   
    location @cache {
    include nginx_cache.conf;
    if ($fenxiLog = 1) {
        access_log /usr/local/nginx/logs/access.m.yohobuy.com.log  fenxi;
    }
    resolver 8.8.8.8;
    proxy_pass http://$pass;
    }   
    location @noCache {g
    if ($fenxiLog = 1) {
        access_log /usr/local/nginx/logs/access.m.yohobuy.com.log  fenxi;
    }
    resolver 8.8.8.8;
    proxy_pass http://$pass;
    }

    所有nginx请求由location /处理,初始化后续逻辑用到的参数,并调用lua模块

  • lua_router.lua lua处理模块

    package.path = "/usr/local/nginx/lua_modules/?.lua"
    local config = require("lua_config")
    for k, v in ipairs(config) do
    if ngx.re.match(ngx.var.uri, v.router) then
        ngx.var.cache = v.cache
        ngx.var.pass= v.proxy_pass
        ngx.var.fenxiLog = v.fenxiLog
        break;
    end
    end
    if ngx.var.cache == "1" then
    ngx.exec("@cache", ngx.var)
    else 
    ngx.exec("@noCache", ngx.var)
    end     

    lua导入配置文件中的路由配置,匹配到当前请求,获得配置数据(缓存配置需要分location内部转发,其他配置项通过变量返回到nginx作用域中)

  • 以及lua配置文件 lua_config.lua

    local config = {
    {
        router = "/product/product/show_", --路由规则
        cache = 1,                         --是否缓存
        proxy_pass = "127.0.0.1:6001",     --反向url
        fenxiLog = 1                       --是否存储log(fenxi)
    },{ 
        router = "/boys",
        cache = 1, 
        proxy_pass = "127.0.0.1:6001",
        fenxiLog = 1
    },{ 
        router = "/girls",
        cache = 0, 
        proxy_pass = "127.0.0.1:6001",
        fenxiLog = 1
    },{ 
        router = "/home",
        cache = 1, 
        proxy_pass = "m.yohobuy.com",
        fenxiLog = 1
    }
    }
    return config

    返回到nginx的location中后根据lua返回变量值处理不同情况的请求