Nginx 實現動態封禁 IP,詳細教程來了

來源:juejin.cn/post/7306038680963579919


需求

爲了封禁某些爬蟲或者惡意用戶對服務器的請求,我們需要建立一個動態的 IP 黑名單。對於黑名單中的 IP ,我們將拒絕提供服務。並且可以設置封禁失效時間

環境準備

設計方案

實現 IP 黑名單的功能有很多途徑:

1、在操作系統層面,配置 iptables,來攔截指定 IP 的網絡請求。

2、在 Web 服務器層面,通過 Nginx 自身的 deny 選項或者 lua 插件配置 IP 黑名單。

3、在應用層面,在處理請求之前檢查客戶端的 IP 地址是否在黑名單中。

爲了方便管理和共享黑名單,通過 nginx + lua + redis 的架構實現 IP 黑名單的功能

配置 nginx.conf

在需要進行限制的 server 的 location 中添加如下配置:

location / {
    # 如果該location 下存在靜態資源文件可以做一個判斷      
    #if ($request_uri ~ .*\.(html|htm|jpg|js|css)) {
    # access_by_lua_file /usr/local/lua/access_limit.lua;   
    #}
    
    access_by_lua_file /usr/local/lua/access_limit.lua; # 加上了這條配置,則會根據 access_limit.lua 的規則進行限流
    alias /usr/local/web/;
    index  index.html index.htm;
}

配置 lua 腳本

/usr/local/lua/access_limit.lua
-- 可以實現自動將訪問頻次過高的IP地址加入黑名單封禁一段時間

--連接池超時回收毫秒
local pool_max_idle_time = 10000
--連接池大小
local pool_size = 100
--redis 連接超時時間
local redis_connection_timeout = 100
--redis host
local redis_host = "your redis host ip"
--redis port
local redis_port = "your redis port"
--redis auth
local redis_auth = "your redis authpassword";
--封禁IP時間(秒)
local ip_block_time= 120
--指定ip訪問頻率時間段(秒)
local ip_time_out = 1
--指定ip訪問頻率計數最大值(次)
local ip_max_count = 3


--  錯誤日誌記錄
local function errlog(msg, ex)
    ngx.log(ngx.ERR, msg, ex)
end

-- 釋放連接池
local function close_redis(red)
    if not red then
        return
    end
    local ok, err = red:set_keepalive(pool_max_idle_time, pool_size)
    if not ok then
        ngx.say("redis connct err:",err)
        return red:close()
    end
end


--連接redis
local redis = require "resty.redis"
local client = redis:new()
local ok, err = client:connect(redis_host, redis_port)
-- 連接失敗返回服務器錯誤
if not ok then
    close_redis(client)
    ngx.exit(ngx.HTTP_INTERNAL_SERVER_ERROR)
end
--設置超時時間
client:set_timeout(redis_connection_timeout)

-- 優化驗證密碼操作 代表連接在連接池使用的次數,如果爲0代表未使用,不爲0代表複用 在只有爲0時才進行密碼校驗
local connCount, err = client:get_reused_times()
-- 新建連接,需要認證密碼
if  0 == connCount then
    local ok, err = client:auth(redis_auth)
    if not ok then
        errlog("failed to auth: ", err)
        return
    end
    --從連接池中獲取連接,無需再次認證密碼
elseif err then
    errlog("failed to get reused times: ", err)
    return
end

-- 獲取請求ip
local function getIp()
    local clientIP = ngx.req.get_headers()["X-Real-IP"]
    if clientIP == nil then
        clientIP = ngx.req.get_headers()["x_forwarded_for"]
    end
    if clientIP == nil then
        clientIP = ngx.var.remote_addr
    end
    return clientIP
end

local cliendIp = getIp();

local incrKey = "limit:count:"..cliendIp
local blockKey = "limit:block:"..cliendIp

--查詢ip是否被禁止訪問,如果存在則返回403錯誤代碼
local is_block,err = client:get(blockKey)
if tonumber(is_block) == 1 then
    ngx.exit(ngx.HTTP_FORBIDDEN)
    close_redis(client)
end

local ip_count, err = client:incr(incrKey)
if tonumber(ip_count) == 1 then
    client:expire(incrKey,ip_time_out)
end
--如果超過單位時間限制的訪問次數,則添加限制訪問標識,限制時間爲ip_block_time
if tonumber(ip_count) > tonumber(ip_max_count) then
    client:set(blockKey,1)
    client:expire(blockKey,ip_block_time)
end

close_redis(client)

總結

以上,便是 Nginx+Lua+Redis 實現的 IP 黑名單功能,具有如下優點:

擴展

1、IP 黑名單的應用場景

IP 黑名單在實際應用中具有廣泛的應用場景,主要用於保護服務器和應用免受惡意攻擊、爬蟲或濫用行爲的影響。下面列舉幾個常見的應用場景:

2、高級功能和改進

除了基本的 IP 黑名單功能外,還可以進行一些高級功能和改進,以提升安全性和用戶體驗:

通過不斷改進和優化 IP 黑名單功能,可以更好地保護服務器和應用的安全。

本文由 Readfog 進行 AMP 轉碼,版權歸原作者所有。
來源https://mp.weixin.qq.com/s/x5vcj_OogUZA83yfs3yMIg