当前位置: 首页 > 科技观察

通过OpenResty实现Nginx动态屏蔽IP

时间:2023-03-23 11:33:12 科技观察

前面提到了nginx在项目中的作用。其实还有很多高级的模块功能。比如今天我们使用OpenResty来防止一些恶意的IP攻击。OpenResty?是一个基于Nginx和Lua的高性能Web平台,集成了大量优秀的Lua库、第三方模块及其大部分依赖。用于轻松构建能够处理超高并发和高扩展性的动态Web应用程序、Web服务和动态网关。官方地址:http://openresty.org/cn/环境搭建本文使用centos7运行安装nginx。这里安装nginx并不是openresty的必备条件,只是为了演示openresty安装后,访问地址会把nginx改成openrestywget下载wgethttp://nginx.org/download/nginx-1.19.5.tar.gz解压执行安装命令tar-zxvfnginx-1.19.5.tar.gz#解压cdnginx-1.19.5#进入目录./configure#Configurationmake#Compilemakeinstall#Installcd/usr/local/nginx/sbin#Switch到nginx命令目录./nginx#启动nginx访问地址安装openresty,首先下载openresty,wgethttps://openresty.org/download/openresty-1.19。3.1.tar.gz(这个版本最后一直无法加载一些lua脚本,最后使用openresty-1.15.8.3版本成功)(这个版本最后一直无法加载一些lua脚本,最后使用openresty-1.15.8.3版本成功)解压安装tar-zxvfopenresty-1.19.3.1.tar.gzcdopenresty-1.19.3.1yuminstallpcre-developenssl-develgcccurl./configure执行makemakeinstall后,我们在openresty中启动nginx。注意,切换到openresty安装的路径/usr/local/openresty/nginx启动/sbin后,访问发现nginx变成了openresty。配置nginx.conf来测试lua功能。可以看到可以使用lua脚本。接下来参考redissdk配置访问lua脚本的请求路径(这里只是一个demo,如果限制访问所有路径,可以拦截/,lua验证通过后再转发请求)lua脚本#Lualocalfunctionclose_redis(redcli)ifnotredclithenreturnend--释放连接(连接池实现)localpool_max_idle_time=10000--毫秒localpool_size=100--连接池大小localok,err=redcli:set_keepalive(pool_max_idle_time,pool_size)ifnotokthenngx_log(ngx_ERR,"setrediskeepaliveerror:",err)endend--连接redislocalredis=require('resty.redis')localredcli=redis.new()redcli:set_timeout(1000)localip="127.0.0.1"---修改变量localport="6379"---修改变量localok,err=redcli:connect(ip,port)ifnotokthenreturnclose_redis(redcli)endlocalclientIP=ngx.var.remote_addr--increKey为请求频率,blackKey黑名单keylocalincrKey="user:"..clientIP..":request:frequency"localblackKey="user:"..clientIP..":black:list"localis_black,err=redcli:get(blackKey)iftonumber(is_black)==1thenngx.exit(403)close_redis(redcli)endinc=redcli:incr(incrKey)ngx.say(inc)ifinc<2theninc=redcli:expire(incrKey,1)endifinc>2then--每秒超过2次访问被认为是非法的,将阻止访问30sredcli:set(blackKey,1)redcli:expire(blackKey,30)endclose_redis(redcli)启动nginx后,request有错误2020/12/0119:13:53[error]2101#0:*2luaentrythreadaborted:runtimeerror:/usr/local/openresty/nginx/lua/access_by_redis.lua:29:attempttocallfield'get_headers'(anilvalue)stacktraceback:coroutine0:/usr/local/openresty/nginx/lua/access_by_redis.lua:inmainchunk,客户端:192.168.49.1,server:localhost,request:"GET/test1HTTP/1.1",host:"192.168.49.131"这个问题困扰我好久了(不要总是一上来就问最新版,吐血)windows版本的openresty没有出现这个问题,liunux一直有问题,最后降低了openresty的版本,实验成功,openresty-1.15.8.3版本正常请求异常请求,最后openresty运行周期图如下如下,你可以从整体上理解openresty