Skip to content

Instantly share code, notes, and snippets.

@felipekm
Last active February 28, 2025 14:48
Show Gist options
  • Save felipekm/e659f66a1cd3b1d9275fe89890f877ea to your computer and use it in GitHub Desktop.
Save felipekm/e659f66a1cd3b1d9275fe89890f877ea to your computer and use it in GitHub Desktop.
NGINX - Complete Script: Automated Log Analysis & Auto-Blocking
#!/bin/bash
# 1️⃣ Adding Execution Permissions & Running as Root
touch setup-fail2ban.sh
chmod +x setup-fail2ban.sh
sudo vim ./setup-fail2ban.sh
server {
listen 80;
server_name your-api.com;
location /api/ {
access_log /var/log/nginx/api.log; # Log all API requests
limit_req zone=req_limit burst=20 nodelay; # Rate limiting
limit_conn conn_limit 5; # Max 5 concurrent connections per IP
if ($http_user_agent ~* (curl|wget|bot|crawler)) {
return 403; # Block bots & scrapers
}
proxy_pass http://backend;
}
}
#!/bin/bash
# Ensure Fail2Ban and NGINX are installed
if ! command -v fail2ban-client &> /dev/null; then
echo "Fail2Ban not found! Installing..."
sudo apt update && sudo apt install fail2ban -y
else
echo "Fail2Ban is already installed."
fi
if ! command -v nginx &> /dev/null; then
echo "NGINX not found! Please install it first."
exit 1
fi
# Enable Fail2Ban
sudo systemctl enable fail2ban --now
# Create Fail2Ban Filter for NGINX Abuse
sudo tee /etc/fail2ban/filter.d/nginx-abuse.conf > /dev/null <<EOF
[Definition]
failregex = <HOST> .* "(GET|POST) /api/.*" 403
EOF
# Configure Fail2Ban to Block Offenders
sudo tee /etc/fail2ban/jail.local > /dev/null <<EOF
[nginx-abuse]
enabled = true
filter = nginx-abuse
logpath = /var/log/nginx/api.log
bantime = 600
maxretry = 5
EOF
# Restart Services
sudo systemctl restart nginx
sudo systemctl restart fail2ban
echo "✅ Fail2Ban is now protecting your API!"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment