Nginx来限定访问掌握的方法有多种,nginx紧张有2个模块掌握,但是那些不支持自定义,非常去世,在大多数场景下并不实用。本日禀享一个:利用openresty+lua+redis 实现封杀频繁恶意访问IP地址,当然这个办法也是有弊端的,那便是不断试用代理 IP之类的,但是浸染还是有的,最少提高了恶意的本钱。
nginx的版本有淘宝nginx,还有春哥的 openresty,但是openresty打包了 nginx 的时候,集成了很多的有用的扩展,特殊是 lua,一个小巧的编程措辞。本文便是:openresty最新稳定版本+lua Lua +redis最新稳定版本 。
详细环境我就不安装了,大家可以利用宝塔面板啥的安装openresty,如果你的原生态的nginx就须要手动安装,网上教程都是有的,也比较大略。

本文是防止别人破解用户登录界面的,只因此一个思路,供给大家进行磋商学习哈,实际生产环境,须要多重考虑各方面的成分。
先在 http 中加载lua 包和 lua 的 c 包
lua_package_path "/usr/local/openresty/lualib/?.lua;;";
lua_package_cpath "/usr/local/openresty/lualib/?.so;;";
server { listen 80; server_name _; access_log /data/wwwlogs/access_nginx.log combined; root /data/wwwroot/default; index index.html index.htm index.php; #例如我防止别人破解我的登录帐号,还有譬如你匹配你的验证码文件进行限定 location /login { default_type 'text/html'; access_by_lua_file "/usr/local/openresty/nginx/lua/access_by_redis.lua"; content_by_lua_block { ngx.say("ok: ") } } location ~ [^/]\.php(/|$) { #fastcgi_pass remote_php_ip:9000; fastcgi_pass unix:/dev/shm/php-cgi.sock; fastcgi_index index.php; include fastcgi.conf; }。。。。。#省略 }
access_by_redis.lua 详细代码如下(已包含详细注释):
ip_bind_time = 30 --封禁IP多永劫光ip_time_out = 6 --指定统计ip访问频率韶光范围connect_count = 10 --指定ip访问频率计数最大值--上面的意思便是6秒内访问超过10次,自动封 IP 30秒。--连接redislocal redis = require "resty.redis"local cache = redis.new()local ok , err = cache.connect(cache,"127.0.0.1","6379")cache:set_timeout(60000)--如果连接失落败,跳转到脚本结尾if not ok then goto Lastendend--查询ip是否在封禁段内,若在则返回403缺点代码--因封禁韶光会大于ip记录韶光,故此处不对ip韶光key和计数key做处理is_bind , err = cache:get("bind_"..ngx.var.remote_addr)if is_bind == '1' then ngx.exit(ngx.HTTP_FORBIDDEN) -- 或者 ngx.exit(403) -- 当然,你也可以返回500缺点啥的,搞一个500页面,提示,亲您访问太频繁啥的。 goto Lastendendstart_time , err = cache:get("time_"..ngx.var.remote_addr)ip_count , err = cache:get("count_"..ngx.var.remote_addr)--如果ip记录韶光大于指定时间间隔或者记录韶光或者不存在ip韶光key则重置韶光key和计数key--如果ip韶光key小于韶光间隔,则ip计数+1,且如果ip计数大于ip频率计数,则设置ip的封禁key为1--同时设置封禁key的过期韶光为封禁ip的韶光if start_time == ngx.null or os.time() - start_time > ip_time_out then res , err = cache:set("time_"..ngx.var.remote_addr , os.time()) res , err = cache:set("count_"..ngx.var.remote_addr , 1)else ip_count = ip_count + 1 res , err = cache:incr("count_"..ngx.var.remote_addr) if ip_count >= connect_count then res , err = cache:set("bind_"..ngx.var.remote_addr,1) res , err = cache:expire("bind_"..ngx.var.remote_addr,ip_bind_time) --fix keys endend--结尾标记::Lastend::local ok, err = cache:close()
末了的效果便是:http://xxxx/login 6秒内访问超过10次,自动封 IP 30秒 。。。这个详细,你也调嘛
本文是很早之前写在博客上的,分享出来希望对大家有用,以为不错,记得关注,点赞,收藏哦。