1. Brief description
In daily production environments, websites may experience malicious requests, DDoS attacks, or other harmful access behaviors. To cope with these situations, dynamic IP ban is a very important security strategy. This blog will introduce how to dynamically block IP through NGINX, from configuration to automation implementation steps.
2. Implementation method
NGINX itself supports simple IP-based access control (such as deny and allow instructions), but to implement dynamic ban, the following solutions are usually combined:
- fail2ban: A commonly used automatic ban tool that detects malicious behavior through monitoring logs and automatically modifys NGINX configuration files.
- nginx dynamic modules: such as ngx_http_limit_req_module and ngx_http_limit_conn_module, which are used to limit the request frequency and concurrency number, and combine scripts to achieve IP ban.
- Redis or database-based scenarios: A list of blocked IPs can be loaded dynamically from storage such as Redis or MySQL through Lua scripts or third-party modules.
3. Use fail2ban to dynamically block it
fail2ban is a common dynamic ban tool that automatically updates NGINX configuration by monitoring malicious behavior in log files. The following are the steps to implement dynamic ban through fail2ban.
3.1 Install fail2ban
sudo apt-get update sudo apt-get install fail2ban
3.2 Configuring NGINX logs
Ensure that logs in the NGINX configuration can log malicious requests. Here is a simple log configuration:
http { log_format main '$remote_addr - $remote_user [$time_local] "$request" ' '$status $body_bytes_sent "$http_referer" ' '"$http_user_agent" "$http_x_forwarded_for"'; access_log /var/log/nginx/ main; }
3.3 Configuring fail2ban rules
Create NGINX filtering rules, edit /etc/fail2ban//, and add the following rules to match malicious behavior in the log:
[Definition] failregex = ^<HOST> -.*"(GET|POST).*HTTP/.*".* 403 ignoreregex =
3.4 Set the jail configuration of fail2ban
In the /etc/fail2ban/ file, add monitoring configuration for NGINX:
[nginx-http-auth] enabled = true port = http,https filter = nginx-http-auth logpath = /var/log/nginx/ maxretry = 5
- logpath: A log file pointing to NGINX.
- maxretry: How many times will the IP be blocked after the setting fails.
3.5 Start fail2ban
sudo service fail2ban restart
This way, when an IP accesses a 403 page 5 times in a row, it will be automatically blocked.
4. Dynamic restrictions on the limit module using NGINX
NGINX's own ngx_http_limit_req_module and ngx_http_limit_conn_module can be used to dynamically limit requests. By setting the request frequency and concurrent connection number, you can effectively resist malicious crawlers and DDoS attacks.
4.1 Configure request frequency limit
Include the following code in the NGINX configuration to limit the frequency of requests for each IP:
http { limit_req_zone $binary_remote_addr zone=one:10m rate=1r/s; server { location / { limit_req zone=one burst=5; } } }
- limit_req_zone: Defines a shared memory area for recording request rate.
- rate=1r/s: Each IP is limited to up to 1 request per second.
4.2 Dynamic adjustment limits
To use Redis and Lua to implement the function of dynamically blocking malicious IP, you can use Redis's counting and expiration features. In Redis, Lua scripts can be used to dynamically detect the request frequency of a certain IP, and once the set threshold is exceeded, the IP will be blocked.
Here is a sample Lua script for blocking malicious IPs. Suppose we will record the number of requests for each IP in Redis and block it after the limit is reached. The following Lua script implements the above logic and sets a limit: if IP requests more than 10 times within 60 seconds, the ban will trigger the ban, and the ban lasts for 3600 seconds (1 hour):
-- Lua Scripts implement dynamic ban malicious intentionsIP local ip = KEYS[1] -- Incoming IP address local max_requests = tonumber(ARGV[1]) -- Maximum number of requests local ban_time = tonumber(ARGV[2]) -- Duration of ban local expire_time = tonumber(ARGV[3]) -- IP Expiration time of counting -- Build Redis key local ip_key = "ip:" .. ip local ban_key = "ban:" .. ip -- examine IP Is it banned if ("EXISTS", ban_key) == 1 then return {false, "IP blocked"} end -- Increase IP Request Count local count = ("INCR", ip_key) -- If it's the first request,设置请求Expiration time of counting if count == 1 then ("EXPIRE", ip_key, expire_time) end -- examine请求次数是否超过最大请求限制 if count > max_requests then -- Reach limit,Banned IP 并设置Banned时间 ("SET", ban_key, "1") ("EXPIRE", ban_key, ban_time) return {false, "Request restrictions have been reached, IP has been blocked"} end -- If the request does not exceed the limit,返回当前Request Count return {true, count}
To execute this Lua script in Redis, you can execute the EVAL command through the Redis client. Assume that the IP address is 192.168.0.1, the request limit is 10 times, the block time is 3600 seconds, and the count expiration time is 60 seconds:
EVAL "<LUA_SCRIPT>" 2 192.168.0.1 10 3600 60
5. Summary
Through the above methods, dynamic ban on IP under NGINX can be achieved, thereby effectively protecting the website from malicious attacks. In practical applications, you can choose the modules that come with fail2ban or NGINX according to your needs, and even combine the database solution to achieve a more complex dynamic blocking mechanism.
This blog provides beginners with ideas and specific configuration examples for NGINX to implement dynamic IP ban. You can flexibly adjust parameters according to business scenarios to improve system security.
This is the article about the steps to implement Nginx dynamic ban on IP. This is all about this article. For more information about Nginx dynamic ban on IP, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!