nginx - 使用 NGINX 和 Lua 限制每个 IP 的请求频率

标签 nginx lua openresty

我的目标是防止基于用户IP的高频请求,google了一下openresty,发现可以用lua玩。所以我写了下面的脚本,我是 Lua 的新手,谁能给我一些关于这个脚本的建议,甚至纠正我。

此脚本用于阻止在 100 秒内请求超过 3 次的请求

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

最佳答案

为什么不直接使用内置的 nginx ngx_http_limit_req_module

例如我们限制来自一个 IP 地址的请求每分钟不超过 2 个。

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

...

server {

    ...

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

关于nginx - 使用 NGINX 和 Lua 限制每个 IP 的请求频率,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31739985/

相关文章:

sockets - 即使我将 chmod-socket 设置为 664 : works on one machine but not the other,uwsgi 也会出现权限被拒绝错误

authentication - Nginx客户端证书授权

c++ - 在 lua 中使用 require 后全局变量丢失

lua - 宇宙飞船的二维轨迹规划与物理

来自上游服务器的 nginx 监控响应

docker - 使用 IDEA 在 Docker 中进行 Openresty LUA 远程调试

nginx - 无法在Lua代码中使用环境变量

ssl - 没有 ssl 证书的域重定向到不同的 ssl 域

c++ - 我应该如何将 lua 函数绑定(bind)到 C++ 函数?

amazon-web-services - 使用 Amazon S3 配置 Nginx 并使用请求的 url 的位置从 S3 获取 html