nginx + lua 限制ip地址访问

2019-09-11 20:08:36 浏览数 (1)

实验环境:docker openresty

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

default.conf 代码如下:

代码语言:javascript复制
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;
    }

}

0 人点赞