nginx + lua 限制ip地址访问

时间:2022-02-24 07:06:44

实验环境: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 ;
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", , ) if not lim then
ngx.log(ngx.ERR, "failed to instantiate a resty.limit.count object: ", err)
return ngx.exit()
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()
end ngx.log(ngx.ERR, "failed to limit count: ", err)
return ngx.exit()
end
} content_by_lua_block {
ngx.say("hello")
} } #error_page /.html; # redirect server error pages to the static page /50x.html
#
error_page /50x.html;
location = /50x.html {
root /usr/local/openresty/nginx/html;
} }