Nginx与Lua
nginx默认不支持lua,需要额外安装luajit,建议使用openrestry
1.安装 openrestry
./configure --prefix=/opt/openresty \
--with-luajit \
--with-pcre \
--with-pcre-jit
--without-http_redis2_module \
--with-http_iconv_module \
--with-http_postgres_module
make &&make install
测试openresty
server {
location /hello {
default_type text/html;
content_by_lua_block {
ngx.say(HelloWorld)
}
}
nginx调用Lua命令
set_by_lua set_by_lua_file 设置nginx变量 可以实现负载均衡的赋值逻辑
access_by_lua access_by_lua_file 请求访问阶段处理用于访问控制
content_by_lua content_by_lua_file 内容处理器
nginx调用lua Api
ngx.var nginx变量
ngx.req.get_headers 获取请求头
ngx.req_get_uri_args 获取url请求参数
ngx.redirect 重定向
ngx.print 输出响应内容体
ngx.say 输出响应内容体
ngx.header 输出响应头
Nginx+lua实现简单灰度发布
upstream test{
server 192.168.1.1:80;
}
upstream prod{
server 192.168.1.2:80;
}
server {
listen 80;
server_name _;
location /lua {
content_by_lua_file redis.lua;
default_type 'text/html';
}
location @test {
proxy_pass http://test;
include proxy_params;
}
location @prod {
proxy_pass http://prod;
include proxy_params;
}
}
redis.lua
//引入redis模块
local redis = require resty.redis
local cache = redis.new()
cache:set_timeout(60000)
连接redis
local ok,err = cache.connect(cache,'localhost',6379)
if not ok then
ngx.exec(@test)
return
end
local local_ip = ngx.req.get_headers()[X_Real_IP]
if local_ip ==nil then
local_ip =ngx.req.get_headers()[X_forwarder_for]
end
if local_ip == nil then
local_ip = ngx.var.remote_addr
end
local intercept = cache:get(local_ip)
if intercept == local_ip then
ngx.exec(@prod)
return
end
ngx.exec(@test)
local ok,err =cache:close()
if not ok then
ngx.say(faild to close:,err)
end
Nginx+lua实现WAF
部署WAF相关代码
git clone http://github.com/loveshell/ngx_lua_waf
cp -r ngx_lua_waf /etc/nginx/waf
nginx配置文件http段添加如下内容
lua_package_path /etc/waf/?.lua
lua_shared_dict limit 10m;
init_by_lua_file /etc/waf/init.lua;
access_by_lua_file /etc/waf/waf/lua;
配置规则
RulePath = /etc/nginx/waf/wafconf
Nginx与Lua
http://www.jcwit.com/article/40/