Authored by 陈峰

nginx-lia.md

No preview for this file type
  1 +###nginx-lua模块集中化管理
  2 +-nginx代码实例
  3 +```
  4 +location / {
  5 + set $pass "127.0.0.1:6001";
  6 + set $cache 0;
  7 + set $fenxiLog 0;
  8 + access_by_lua_file /usr/local/nginx/lua_modules/lua_router.lua;
  9 +}
  10 +location @cache {
  11 + include nginx_cache.conf;
  12 + if ($fenxiLog = 1) {
  13 + access_log /usr/local/nginx/logs/access.m.yohobuy.com.log fenxi;
  14 + }
  15 + resolver 8.8.8.8;
  16 + proxy_pass http://$pass;
  17 +}
  18 +location @noCache {
  19 + if ($fenxiLog = 1) {
  20 + access_log /usr/local/nginx/logs/access.m.yohobuy.com.log fenxi;
  21 + }
  22 + resolver 8.8.8.8;
  23 + proxy_pass http://$pass;
  24 +}
  25 +```
  26 +所有nginx请求由`` location / ``处理,初始化后续逻辑用到的参数,并调用lua模块
  27 +-lua_router.lua lua处理模块
  28 +```
  29 +package.path = "/usr/local/nginx/lua_modules/?.lua"
  30 +local config = require("lua_config")
  31 +for k, v in ipairs(config) do
  32 + if ngx.re.match(ngx.var.uri, v.router) then
  33 + ngx.var.cache = v.cache
  34 + ngx.var.pass= v.proxy_pass
  35 + ngx.var.fenxiLog = v.fenxiLog
  36 + break;
  37 + end
  38 +end
  39 +if ngx.var.cache == "1" then
  40 + ngx.exec("@cache", ngx.var)
  41 +else
  42 + ngx.exec("@noCache", ngx.var)
  43 +end
  44 +```
  45 +lua导入配置文件中的路由配置,匹配到当前请求,获得配置数据(缓存配置需要分location内部转发,其他配置项通过变量返回到nginx作用域中)
  46 +-以及lua配置文件 lua_config.lua
  47 +```
  48 +local config = {
  49 + {
  50 + router = "/product/product/show_", --路由规则
  51 + cache = 1, --是否缓存
  52 + proxy_pass = "127.0.0.1:6001", --反向url
  53 + fenxiLog = 1 --是否存储log(fenxi)
  54 + },{
  55 + router = "/boys",
  56 + cache = 1,
  57 + proxy_pass = "127.0.0.1:6001",
  58 + fenxiLog = 1
  59 + },{
  60 + router = "/girls",
  61 + cache = 0,
  62 + proxy_pass = "127.0.0.1:6001",
  63 + fenxiLog = 1
  64 + },{
  65 + router = "/home",
  66 + cache = 1,
  67 + proxy_pass = "m.yohobuy.com",
  68 + fenxiLog = 1
  69 + }
  70 +}
  71 +return config
  72 +```
  73 +返回到nginx的location中后根据lua返回变量值处理不同情况的请求