How to Auto‑Block Malicious IPs with Nginx: Script & Crontab Guide
Learn step‑by‑step how to create an Nginx configuration file, use AWK and shell scripts to detect IPs with more than 60 requests per minute, automatically generate deny rules, and schedule the process with crontab to keep your personal site safe from attacks.
Personal website keeps getting attacked? Here is an automatic IP‑blocking script using Nginx.
1. Create a blockip.conf file in the Nginx conf directory. deny 1.2.3.4; 2. Add the IPs you want to block to this file using the format shown above.
3. Include the file in the Nginx HTTP configuration: include blockips.conf; 4. Reload Nginx to apply the changes. /usr/local/nginx/sbin/nginx -s reload After reloading, the offending IPs will receive a 403 response.
How to Implement Automatic IP Blocking with Nginx
Use AWK to analyze access.log and record IPs with more than 60 requests per minute, then block them via Nginx.
Write a shell script to automate the whole process.
Schedule the script with crontab to run every minute.
Step 1: AWK Statistics on access.log
awk '{print $1}' access.log | sort | uniq -c | awk '{if($1>60)print $0}'
# 1. Extract IP column
# 2. Sort and count occurrences
# 3. Print IPs with more than 60 hitsStep 2: Shell Script (with comments)
# Clear previous block list
echo "" > /usr/local/nginx/conf/blockip.conf
# Get list of offending IPs
ip_list=$(awk '{print $1}' access.log | sort | uniq -c | awk '{if($1>60)print $0}')
if test -z "$ip_list"; then
echo "Empty" >> /usr/local/nginx/logs/11.log
/usr/local/nginx/sbin/nginx -s reload
else
echo "deny $ip_list" > /usr/local/nginx/conf/blockip.conf
ip_list2=$(awk '{print $3}' /usr/local/nginx/conf/blockip.conf)
echo "deny $ip_list2" > /usr/local/nginx/conf/blockip.conf
/usr/local/nginx/sbin/nginx -s reload
echo "" > /usr/local/nginx/logs/access.log
fiStep 3: Schedule with crontab
crontab -e
* * * * * cd /usr/local/nginx/logs/ && sh ip_test.sh # run every minute
systemctl restart crond.serviceSigned-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
Open Source Linux
Focused on sharing Linux/Unix content, covering fundamentals, system development, network programming, automation/operations, cloud computing, and related professional knowledge.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
