Jusene's Blog

OpenResty IP访问控制

字数统计: 445阅读时长: 2 min
2019/09/03 Share
  • 创建项目
1
mkdir ipban
2
cd ipban
3
mkdir config logs
4
cd config
5
touch nginx.conf
  • nginx.conf
1
worker_processes auto;
2
events {
3
    worker_connections 10240
4
    use epoll;
5
}
6
7
http {
8
    server {
9
        listen 80;
10
        server_name _;
11
        location / {
12
            default_type "text/html";
13
            access_by_lua_file /data/lua/block.lua;
14
            content_by_lua_block {
15
                ngx.say('<h1>Access Openresty</h1>')
16
            }
17
        }
18
    }
19
}
  • 安装redis模块
1
# 搜索redis模块
2
opm search redis
3
4
# 安装redis模块
5
opm install openresty/lua-resty-redis
6
7
# 安装redis服务
8
yum install -y redis
  • block.lua
1
local redis_ip = "127.0.0.1"
2
local redis_port = 6379
3
4
-- 黑名单
5
local black_list = {"10.211.55.3"}
6
-- 白名单
7
local white_list = {"10.211.55.2"}
8
9
-- 监测周期
10
local ttl = 60
11
-- 触发阈值
12
local bktimes = 10
13
-- 拦截时间
14
local block_ttl = 600
15
-- 客户地址
16
local ip = ngx.var.remote_addr
17
18
for i, v in ipairs(black_list) do
19
    if v == ip then
20
        ngx.say("blocked")
21
        return ngx.exit(403)
22
    end
23
end
24
25
for i, v in ipairs(white_list) do
26
    if v == ip then
27
        return ngx.exit(ngx.HTTP_OK)
28
    end
29
end
30
31
local redis = require "resty.redis"
32
local rds = redis:new()
33
rds:set_timeout(1000) -- 超时1秒
34
35
local ok, err = rds:connect(redis_ip, redis_port)
36
if not ok then
37
    ngx.say("fail to connect: ", err)
38
    return
39
end
40
41
local iptimes, err = rds:get(ip)
42
43
if iptimes ~= ngx.null then -- 监测iptimes是否为空 
44
    if iptimes == "-1" then -- 值为-1时封禁
45
        ngx.say("blocked")
46
        return ngx.exit(403)
47
    else
48
        last_ttl = red:ttl(ip)
49
        if last_ttl == "-1" then -- ttl为-1为没有设置ttl值
50
            rds:set(ip, 0)
51
            rds:expire(ip, ttl)
52
            return ngx.exit(ngx.HTTP_OK)
53
        end
54
        times = tonumber(rds:get(ip))+1
55
        if times < bktimes then
56
            rds:set(ip, times)
57
            rds:expire(ip, last_ttl)
58
            return ngx.exit(ngx.HTTP_OK)
59
        else
60
            rds:set(ip, -1)
61
            rds:expire(ip, block_ttl)
62
            return ngx.exit(ngx.HTTP_OK)
63
        end
64
    end
65
else
66
    rds:set(ip, 1)
67
    red:expire(ip, ttl)
68
    return ngx.exit(ngx.HTTP_OK)
69
end
  • 启动项目
1
# 启动
2
openresty -p ./ipban
3
4
# 重载配置
5
openresty -p ./ipban -s reload
CATALOG