欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

nginx + lua 限制ip地址访问

程序员文章站 2022-12-23 07:51:08
实验环境:docker + openresty 我限制的5秒钟内允许访问两次效果图: default.conf 代码如下: ......

实验环境:docker + openresty

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

nginx + lua 限制ip地址访问

 

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;
    }

}