lua+nginx实现黑名单禁止访问

Responsive image

可以使用基于 Nginx 与 Lua 的高性能 Web 平台OpenResty。 OpenResty地址

安装简单,略去。

 # 分配内存
    lua_shared_dict ip_blacklist 1m;

    server {
        listen       80;
        server_name  localhost;

        root   E:/www/web/test;

        access_log  logs/host.access.log ;
        error_log  logs/host.error.log;

        location / {
            access_by_lua_file ../lua/black.lua;
            index  index.html index.htm;
        }


        error_page   500 502 503 504  /50x.html;
        location = /50x.html {
            root   html;
        }


        location ~ \.php$ {
        # 指定lua文件
            access_by_lua_file "D:\openresty-1.15.8.1-win64/lua/black.lua";
            fastcgi_pass   127.0.0.1:9000;
            fastcgi_index  index.php;
            fastcgi_param  SCRIPT_FILENAME  $document_root$fastcgi_script_name;
            include        fastcgi_params;
        }
    }

black.lua

local redis_host    = "127.0.0.1" -- 这里一定是redis的IP地址
local redis_port    = "6379"

-- connection timeout for redis in ms. don't set this too high!
local redis_connection_timeout = 1000

-- check a set with this key for blacklist entries
local redis_key     = "ip_blacklist"

-- cache lookups for this many seconds
local cache_ttl     = 100

-- end configuration

local ip                = ngx.var.remote_addr
local ip_blacklist              = ngx.shared.ip_blacklist
local last_update_time  = ip_blacklist:get("last_update_time");

-- only update ip_blacklist from Redis once every cache_ttl seconds:
if last_update_time == nil or last_update_time < ( ngx.now() - cache_ttl ) then

  local redis = require "resty.redis";
  local red = redis:new();

  red:set_timeout(redis_connect_timeout);

  local ok, err = red:connect(redis_host, redis_port);

  if not ok then
    ngx.say("redis connect failed: ", err)
    ngx.log(ngx.DEBUG, "Redis connection error while retrieving ip_blacklist: " .. err);
    return ngx.exit(ngx.HTTP_INTERNAL_SERVER_ERROR)
  else
    -- local res, err = red:auth("foobared") -- 配置redis的密码

    --if not res then
        --ngx.say("redis auth is error: ", err)
        --return
    --end
    red:select(0) -- 设置redis的db
    local new_ip_blacklist, err = red:smembers(redis_key);
    if err then
      ngx.log(ngx.DEBUG, "Redis read error while retrieving ip_blacklist: " .. err);
    else
      -- replace the locally stored ip_blacklist with the updated values:
      ip_blacklist:flush_all();
      for index, banned_ip in ipairs(new_ip_blacklist) do
        ip_blacklist:set(banned_ip, true);
      end

      -- update time
      ip_blacklist:set("last_update_time", ngx.now());
    end
  end
end


if ip_blacklist:get(ip) then
  --ngx.say(ip)
  ngx.log(ngx.DEBUG, "Banned IP detected and refused access: " .. ip);
  return ngx.exit(ngx.HTTP_FORBIDDEN);
end

猜你喜欢

转载自blog.csdn.net/liuxl57805678/article/details/103139146