yunfeng.guo
yunfeng.guo

Reputation: 185

Limit requests frequency of each IP using NGINX & Lua

My goal is to prevent the high frequent request based on user IP, and i google the openresty and found it can be played with Lua. So i wrote the following script, i'm a newbie to Lua, could anyone give me some advice on this script, or even correct me.

this script is to block request which requests over 3 times in 100s

local limit_request_times = 3
local expire_time = 100

local user_ip = ngx.var.remote_addr

-- ngx.say("user_ip: ", user_ip)

local redis = require "resty.redis"
local red = redis:new()
red:set_timeout(1000)
local ok, err = red:connect("127.0.0.1", 6379)
if not ok then
    ngx.say("failed to connect: ", err)
    return
end


local res, err = red:get(user_ip)
if res == ngx.null then
    ngx.say("no request record, add this user_ip to redis")
    ok, err = red:set(user_ip, 1)
    if not ok then
        -- ngx.say("add user_ip failed")
        ngx.exit(ngx.HTTP_FORBIDDEN)
        return
    else
        red:expire(user_ip, expire_time)
    end
else
    if tonumber(res) == limit_request_times then
        -- ngx.say("request reach max limit times")
        ngx.exit(403)
        return
    else
        ok, err = red:incr(user_ip)
        if not ok then
            ngx.say("failed to increment request times")
            return
        else
            ngx.say("increment request times: ", res + 1)
        end
    end 
end

Upvotes: 3

Views: 3811

Answers (2)

Hett
Hett

Reputation: 3823

Also you can use resty.limit.conn and/or resty.limit.req modules via Lua https://nginx-extras.getpagespeed.com/lua/limit-traffic/

Upvotes: 0

xfeep
xfeep

Reputation: 1111

Why not just use nginx build-in ngx_http_limit_req_module?

e.g. We limit not more than 2 requests per minute from one IP address。

http {
limit_req_zone $binary_remote_addr zone=one:10m rate=2r/m;

...

server {

    ...

    location /search/ {
        limit_req zone=one burst=3 nodelay;
    }

Upvotes: 9

Related Questions