How to Automatically Block Malicious IPs with Nginx and Shell Scripts
This guide walks you through creating a block list file, configuring Nginx to deny offending IPs, using AWK to extract high‑frequency visitors from access logs, writing a shell script to automate the process, and scheduling it with crontab for continuous protection.
1. Create a file blockip.conf in Nginx's conf directory.
2. Add the IPs you want to block, each line in the form: deny 1.2.3.4; 3. Include the file in the HTTP block of Nginx configuration:
include blockips.conf;4. Reload Nginx:
/usr/local/nginx/sbin/nginx -s reload5. After reload the IPs will be blocked and you will receive a 403 response.
Thought: How to implement automatic IP blocking with Nginx?
Use AWK to analyze access.log and find IPs with more than 60 requests per minute, then block them with Nginx.
Write a shell script that performs the whole process.
Schedule the script with crontab.
Step 1: AWK statistics – extract IPs from access.log:
awk '{print $1}' access.log | sort | uniq -cd | awk '{if($1>60)print $0}'Step 2: Shell script (with comments)
# Clear previous block list
echo "" > /usr/local/nginx/conf/blockip.conf
# Get IPs with >60 requests per minute
ip_list=$(awk '{print $1}' access.log | sort | uniq -cd | awk '{if($1>60)print $0}')
# If no IPs, log and reload
if test -z "$ip_list"; then
echo "empty" >> /usr/local/nginx/logs/11.log
/usr/local/nginx/sbin/nginx -s reload
else
# Write deny rules
echo "deny $ip_list" > /usr/local/nginx/conf/blockip.conf
# Remove line numbers from the file
ip_list2=$(awk '{print $3}' /usr/local/nginx/conf/blockip.conf)
echo "deny $ip_list2;" > /usr/local/nginx/conf/blockip.conf
# Reload Nginx
/usr/local/nginx/sbin/nginx -s reload
# Clear old access log
echo "" > /usr/local/nginx/logs/access.log
fiStep 3: Crontab scheduling
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.
