配置nginx环境
安装Lua
宝塔环境默认是有安装lua的,如果没有的话,可以自己安装
1. 获取并解压lua安装包
curl -R -O http://www.lua.org/ftp/lua-5.3.0.tar.gz
tar zxf lua-5.3.0.tar.gz
2. 安装lua脚本
cd lua-5.3.0
make && make install PREFIX=/usr/local/LuaJIT
3. 配置环境变量
vim /etc/profile
export LUAJIT_LIB=/usr/local/LuaJIT/lib
export LUAJIT_INC=/usr/local/LuaJIT/include/luajit-2.0
安装nginx的lua模块
方法一:使用 宝塔自带的 nginx openresty
方法二:编译安装 nginx的时候添加lua相关模块
模块参数
--add- module=/home/ngx_cache_purge-2.3 --add-module=/home/lua-nginx-module-0.10.9rc7 --add- module=/home/ngx_devel_kit-0.3.0
前置脚本:
wget https://github.com/simpl/ngx_devel_kit/archive/v0.3.0.tar.gz
wget https://github.com/openresty/lua-nginx-module/archive/v0.10.9rc7.tar.gz
使用lua对nginx简单限流
配置站点 .conf 文件
lua_code_cache off; # 禁止缓存lua文件,生产环境不要使用,默认是 on
lua_shared_dict url_limit 5m; # 声明共享空间,用于lua调用
server
{
...
location /xianliu {
default_type 'text/html';
access_by_lua_file /lua/xianliu.lua; # 调用lua文件
content_by_lua 'ngx.say("hello world")';
}
}
编写lua代码
ngx.header.content_type="text/html;charset=utf-8";
local request_uri_without_args = ngx.re.sub(ngx.var.request_uri,"\\?.*","");
--限流计数
function limit_url_check(key, s)
-- 获取nginx共享空间的变量
local yyy_limit = ngx.shared.url_limit;
--每秒钟限制
local key_s_limit = key..os.date("%Y-%m-%d%H:%M:%S",ngx.time());
local req_key_s,_ = yyy_limit:get(key_s_limit);
--每秒处理
if req_key_s then
yyy_limit:incr(key_s_limit, 1);
if req_key_s>s then
return true
end
else
yyy_limit:set(key_s_limit, 1, 1);
end
return false
end
if ngx.re.match(request_uri_without_args, "/xianliu(.*)") then
if limit_url_check("appcartinfo",3) then
ngx.say( '{"code": 524,"msg": "当前访问的用户过多,请稍后再 试!","alert": "当前访问的用户过多,请稍后再试!"}' );
return
end
end
测试
疯狂访问:http://192.168.1.45/xianliu
一秒内请求超过3次,就会返回:
{"code": 524,"msg": "当前访问的用户过多,请稍后再 试!","alert": "当前访问的用户过多,请稍后再试!"}
至此,简单的nginx+lua限流就实地完成了