|
|
###nginx-lua模块集中化管理
|
|
|
-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 {
|
|
|
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返回变量值处理不同情况的请求 |
|
|
\ No newline at end of file |
...
|
...
|
|