Lanyiyun: nginx+lua+ngx+redis realizes WAF referencing web firewall to dynamically block frequently accessed IPs

Use Lua and ngx_lua modules and Redis in Nginx to implement Web Application Firewall (WAF) to dynamically block frequently accessed IP addresses. This can be completed through the following steps:

  1. Install Nginx and ngx_lua modules:
    First, make sure Nginx is installed and the ngx_lua module is compiled and installed. You can use openresty (a suite that integrates Nginx and ngx_lua) or manually compile Nginx and add the ngx_lua module.
  2. Install Redis:
    Install Redis to store a list of frequently accessed IP addresses. You can download the latest version from the Redis official website and install it according to the official documentation.
  3. Configure Nginx:
    In the Nginx configuration file, add the following to reference the ngx_lua module and configure the WAF rules:
http {
    lua_shared_dict ip_dict 10m;

    server {
        listen 80;
        server_name example.com;

        location / {
            access_by_lua_block {
                local ip = ngx.var.remote_addr
                local key = "ip:" .. ip
                local count = tonumber(ngx.shared.ip_dict:get(key) or 0)
                local limit = 100  -- 设置频繁访问限制次数

                if count > limit then
                    ngx.log(ngx.ERR, "IP " .. ip .. " has exceeded the limit")
                    return ngx.exit(ngx.HTTP_FORBIDDEN)
                end

                ngx.shared.ip_dict:set(key, count + 1, 60)  -- 设置统计时间窗口为1分钟
            }

            # 正常的后端处理逻辑
        }
    }
}

In the above configuration, we used the ngx_lua module  lua_shared_dictto create a shared dictionary  ip_dictto store the number of visits to the IP address. In  access_by_lua_block, we get the client IP address and use it as a key to look up the number of visits for that IP in the shared dictionary. If the number of accesses exceeds the set limit, access is denied and HTTP_FORBIDDEN (403) status code is returned.

  1. Block IPs:
    If you want to dynamically block frequently accessed IPs, you can add frequently accessed IPs to the Redis blacklist in the WAF configuration, and then Nginx will ban the IPs based on the blacklist in Redis.

The above are the brief steps to use Nginx+Lua+ngx_lua module+Redis to implement Web Firewall (WAF) to dynamically block frequently accessed IPs. This scheme can effectively protect the web server from frequent access and malicious requests. Please note that specific configurations and rules are adjusted according to actual needs to ensure the security and effectiveness of WAF.

Guess you like

Origin blog.csdn.net/tiansyun/article/details/133363946