bashintermediate
Fail2ban Security Configuration
Configure Fail2ban to protect SSH and Nginx from brute force attacks with custom jail rules.
bashPress ⌘/Ctrl + Shift + C to copy
#!/usr/bin/env bash
set -euo pipefail
# Install fail2ban
sudo apt update && sudo apt install -y fail2ban
# Create local config (never edit jail.conf directly)
sudo tee /etc/fail2ban/jail.local > /dev/null << 'EOF'
[DEFAULT]
bantime = 3600
findtime = 600
maxretry = 5
destemail = admin@example.com
sender = fail2ban@example.com
action = %(action_mwl)s
[sshd]
enabled = true
port = ssh
filter = sshd
logpath = /var/log/auth.log
maxretry = 3
bantime = 86400
[nginx-http-auth]
enabled = true
port = http,https
filter = nginx-http-auth
logpath = /var/log/nginx/error.log
maxretry = 5
[nginx-limit-req]
enabled = true
port = http,https
filter = nginx-limit-req
logpath = /var/log/nginx/error.log
maxretry = 10
findtime = 120
bantime = 600
EOF
# Enable and start
sudo systemctl enable fail2ban
sudo systemctl restart fail2ban
# Check status
sudo fail2ban-client status
sudo fail2ban-client status sshd
# Unban an IP
# sudo fail2ban-client set sshd unbanip 192.168.1.100
# View banned IPs
# sudo fail2ban-client get sshd bannedUse Cases
- Protecting SSH from brute force attacks
- Rate limiting web server abuse
- Automated intrusion prevention
Tags
Related Snippets
Similar patterns you can reuse in the same workflow.
bashintermediate
Nginx SSL Setup with Certbot
Bash script to install and configure SSL certificates with Certbot for Nginx with auto-renewal.
Best for: Setting up HTTPS for production websites
#ssl#certbot
bashintermediate
Nginx Rate Limiting Configuration
Nginx rate limiting with multiple zones for API and login routes, burst handling, and custom error pages.
Best for: Protecting APIs from abuse and DDoS
#nginx#rate-limiting
typescriptintermediate
In-Memory Rate Limiter for Express
Token bucket rate limiter middleware for Express with configurable window and max requests per IP.
Best for: API abuse prevention
#express#rate-limit
typescriptadvanced
JWT Refresh Token Rotation
Implement secure token rotation with short-lived access tokens and one-time-use refresh tokens.
Best for: Secure API authentication
#jwt#authentication