nginx + lua 限制ip地址访问

本文介绍如何在Docker环境下使用OpenResty进行访问频率限制,通过lua_shared_dict和resty.limit.count模块实现5秒内同一IP仅允许访问两次的效果。代码示例展示了具体的配置方法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

实验环境:docker + openresty

我限制的5秒钟内允许访问两次效果图:

 

default.conf  代码如下:

lua_shared_dict my_limit_count_store 100m;

init_by_lua_block {
    require "resty.core"
}

server {
    listen       80;
    server_name  localhost;

    #charset koi8-r;
    #access_log  /var/log/nginx/host.access.log  main;

    location /hello {
        default_type text/html;

         access_by_lua_block {
                local limit_count = require "resty.limit.count"
                local lim, err = limit_count.new("my_limit_count_store", 2, 5)
                
                if not lim then
                    ngx.log(ngx.ERR, "failed to instantiate a resty.limit.count object: ", err)
                    return ngx.exit(500)
                end

                local key = ngx.var.binary_remote_addr
                local delay, err = lim:incoming(key, true)
                
                if not delay then
                    if err == "rejected" then
                        return ngx.exit(503)
                    end

                    ngx.log(ngx.ERR, "failed to limit count: ", err)
                    return ngx.exit(500)
                end
         }


         content_by_lua_block {
                ngx.say("hello")
         }

    }

    #error_page  404              /404.html;

    # redirect server error pages to the static page /50x.html
    #
    error_page   500 502 503 504  /50x.html;
    location = /50x.html {
        root   /usr/local/openresty/nginx/html;
    }

}

 

转载于:https://www.cnblogs.com/itsuibi/p/10788496.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值