背景
为了封禁某些爬虫或者恶意用户对服务器的请求,我们需要建立一个动态的 IP 黑名单。对于黑名单之内的 IP ,拒绝提供服务。并且可以设置失效
1.安装Openresty(编译安装)
1
| wget https://openresty.org/download/openresty-1.19.3.1.tar.gz
|
下载缓存插件
1
| wget http://labs.frickle.com/files/ngx_cache_purge-2.3.tar.gz
|
编译OpenResty
选择需要的插件启用, –with-Components
激活组件,–without
则是禁止组件 ,–add-module
是安装第三方模块。
进入刚刚解压好的openresty-1.19.3.1
根目录下执行命令
1
| ./configure --prefix=/usr/local/openresty --with-luajit --without-http_redis2_module --with-http_stub_status_module --with-http_v2_module --with-http_gzip_static_module --with-http_sub_module --add-module=/usr/local/openresty-1.19.3.1/modules/ngx_cache_purge-2.3
|
–prefix=/usr/local/openresty: 刚自己创建的目录,用来存放编译后的openresty
–add-module=/usr/local/openresty-1.19.3.1/xxx: 存放第三方插件的位置
2.安装redis
这里我是基于docker安装的redis
1
| docker run --restart=always -p 6379:6379 --name myredis -d redis:7.0.12 --requirepass xxx
|
- -requirepass 是redis密码
3.写lua脚本
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50
| ip_bind_time = 30 ip_time_out = 6 connect_count = 10
local redis = require "resty.redis" local cache = redis.new() local ok , err = cache.connect(cache,"127.0.0.1","6379")
local res, err = cache:auth("xxx") cache:set_timeout(60000)
if not ok then goto Lastend end
is_bind , err = cache:get("bind_"..ngx.var.remote_addr) if is_bind == '1' then ngx.exit(ngx.HTTP_FORBIDDEN) goto Lastend end start_time , err = cache:get("time_"..ngx.var.remote_addr) ip_count , err = cache:get("count_"..ngx.var.remote_addr)
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) end end
::Lastend:: local ok, err = cache:close()
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116
| worker_processes 1;
events { worker_connections 1024; } http { include mime.types; default_type application/octet-stream; sendfile on; keepalive_timeout 65; server { listen 80; server_name localhost; location / { root html; index index.html index.htm; access_by_lua_file "/usr/local/openresty/nginx/lua/access_by_redis.lua"; } error_page 500 502 503 504 /50x.html; location = /50x.html { root html; } } }
|
启动下就可以了