Set up comprehensive Apache protection against DDoS attacks and malicious traffic using mod_evasive for rate limiting, mod_security with OWASP rules for web application firewall capabilities, and fail2ban integration for automated IP blocking.
Prerequisites
- Root or sudo access
- Apache web server
- Internet connection for package installation
- Basic knowledge of Apache configuration
What this solves
This tutorial helps you protect your Apache web server from DDoS attacks, brute force attempts, and malicious traffic patterns. You'll implement multiple layers of protection including rate limiting, web application firewall rules, and automated IP blocking to maintain server availability under attack conditions.
Step-by-step installation
Update system packages
Start by updating your package manager to ensure you get the latest security patches and module versions.
sudo apt update && sudo apt upgrade -y
Install Apache and security modules
Install Apache web server along with mod_evasive for DDoS protection and mod_security for web application firewall capabilities.
sudo apt install -y apache2 libapache2-mod-evasive libapache2-mod-security2 modsecurity-crs
Install mod_limitipconn for connection limiting
Add mod_limitipconn to limit the number of simultaneous connections per IP address, providing additional protection against connection flooding attacks.
sudo apt install -y libapache2-mod-limitipconn
Install fail2ban for automated IP blocking
Install fail2ban to automatically block IP addresses that exhibit suspicious behavior patterns detected in Apache logs.
sudo apt install -y fail2ban
Enable Apache security modules
Enable the installed security modules in Apache configuration. These modules will be loaded when Apache starts.
sudo a2enmod evasive
sudo a2enmod security2
sudo a2enmod limitipconn
sudo a2enmod headers
sudo a2enmod rewrite
Configure mod_evasive for DDoS protection
Create mod_evasive configuration to limit request rates and protect against DoS attacks. This configuration sets thresholds for page requests and site requests per second.
DOSHashTableSize 512
DOSPageCount 3
DOSPageInterval 1
DOSSiteCount 50
DOSSiteInterval 1
DOSBlockingPeriod 600
DOSLogDir "/var/log/apache2"
DOSEmailNotify admin@example.com
DOSWhitelist 127.0.0.1
DOSWhitelist 203.0.113.0/24
Configure mod_security with OWASP Core Rule Set
Set up mod_security with the OWASP Core Rule Set to protect against web application attacks including SQL injection, XSS, and other common vulnerabilities.
sudo cp /etc/modsecurity/modsecurity.conf-recommended /etc/modsecurity/modsecurity.conf
Configure mod_security rules
Enable mod_security in blocking mode and configure logging for security events. This configuration activates the web application firewall protection.
sudo sed -i 's/SecRuleEngine DetectionOnly/SecRuleEngine On/' /etc/modsecurity/modsecurity.conf
sudo sed -i 's/SecAuditLogParts ABIJDEFHZ/SecAuditLogParts ABCEFHJKZ/' /etc/modsecurity/modsecurity.conf
Create Apache security configuration
Create a comprehensive security configuration file that includes mod_security, mod_evasive, and mod_limitipconn settings for your virtual hosts.
# ModSecurity Configuration
SecRuleEngine On
SecRequestBodyAccess On
SecRequestBodyLimit 13107200
SecRequestBodyNoFilesLimit 131072
SecRequestBodyInMemoryLimit 131072
SecRequestBodyLimitAction Reject
SecResponseBodyAccess Off
SecResponseBodyMimeType text/plain text/html text/xml
SecResponseBodyLimit 524288
SecResponseBodyLimitAction ProcessPartial
SecTmpDir /tmp/
SecDataDir /tmp/
Rate Limiting with mod_limitipconn
LoadModule limitipconn_module modules/mod_limitipconn.so
MaxConnPerIP 20
NoIPLimit image/*
Security Headers
Header always set X-Frame-Options DENY
Header always set X-Content-Type-Options nosniff
Header always set X-XSS-Protection "1; mode=block"
Header always set Strict-Transport-Security "max-age=31536000; includeSubDomains"
Header always set Referrer-Policy "strict-origin-when-cross-origin"
Header always set Content-Security-Policy "default-src 'self'"
Hide Apache Version
ServerTokens Prod
ServerSignature Off
Enable security configuration
Enable the security hardening configuration and create necessary directories for mod_evasive logging.
sudo a2enconf security-hardening
sudo mkdir -p /var/log/mod_evasive
sudo chown www-data:www-data /var/log/mod_evasive
sudo chmod 755 /var/log/mod_evasive
Configure fail2ban for Apache protection
Set up fail2ban jails to automatically block IP addresses that trigger mod_security rules or show suspicious behavior patterns in Apache logs.
[apache-auth]
enabled = true
port = http,https
filter = apache-auth
logpath = /var/log/apache2/error.log
maxretry = 3
bantime = 3600
findtime = 600
[apache-badbots]
enabled = true
port = http,https
filter = apache-badbots
logpath = /var/log/apache2/access.log
maxretry = 2
bantime = 86400
findtime = 600
[apache-noscript]
enabled = true
port = http,https
filter = apache-noscript
logpath = /var/log/apache2/access.log
maxretry = 3
bantime = 3600
findtime = 600
[apache-overflows]
enabled = true
port = http,https
filter = apache-overflows
logpath = /var/log/apache2/access.log
maxretry = 2
bantime = 3600
findtime = 600
[apache-modsecurity]
enabled = true
port = http,https
filter = apache-modsecurity
logpath = /var/log/apache2/error.log
maxretry = 2
bantime = 86400
findtime = 600
Create custom fail2ban filter for mod_security
Create a custom filter to detect mod_security rule violations and automatically block attacking IP addresses.
[Definition]
failregex = ^.\[error\].\[client \] ModSecurity:.*$
^.\[error\].\[client \] ModSecurity: Warning.*$
^.\[error\].\[client \] ModSecurity: Access denied.*$
ignoreregex =
[INCLUDES]
before = common.conf
Start and enable services
Start Apache and fail2ban services, then enable them to start automatically on system boot.
sudo systemctl restart apache2
sudo systemctl enable apache2
sudo systemctl restart fail2ban
sudo systemctl enable fail2ban
Configure firewall rules
Open HTTP and HTTPS ports in your firewall while maintaining security. This allows legitimate web traffic while blocking unauthorized access.
sudo ufw allow 'Apache Full'
sudo ufw enable
Verify your setup
Check that all security modules are loaded and services are running properly.
sudo apache2ctl -M | grep -E '(evasive|security|limitipconn)'
sudo systemctl status apache2
sudo systemctl status fail2ban
sudo fail2ban-client status
Test mod_evasive protection by making rapid requests:
for i in {1..10}; do curl -I http://your-server-ip/; done
Check security logs for mod_security events:
sudo tail -f /var/log/apache2/error.log
sudo tail -f /var/log/apache2/modsec_audit.log
Common issues
| Symptom | Cause | Fix |
|---|---|---|
| Apache fails to start | Module configuration error | Check sudo apache2ctl configtest for syntax errors |
| mod_security blocks legitimate traffic | OWASP rules too strict | Review and whitelist specific rule IDs in mod_security config |
| mod_evasive not blocking requests | Incorrect threshold settings | Lower DOSPageCount and DOSSiteCount values |
| fail2ban not detecting attacks | Log path mismatch | Verify log paths in jail configuration match actual Apache log locations |
| High false positives in blocking | Aggressive rate limiting | Increase MaxConnPerIP and adjust mod_evasive thresholds |
| ModSecurity audit log not created | Permission issues | Ensure Apache user can write to log directory with chown www-data:www-data |
Next steps
- Configure Linux firewall rules with fail2ban for SSH brute force protection and intrusion prevention
- Configure ModSecurity 3 web application firewall with OWASP Core Rule Set for advanced threat protection
- Configure Apache SSL hardening with perfect forward secrecy
- Setup centralized log aggregation with Elasticsearch 8, Logstash 8, and Kibana 8 (ELK Stack)
- Configure Apache security headers and Content Security Policy
Automated install script
Run this to automate the entire setup
#!/usr/bin/env bash
set -euo pipefail
# Colors
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
NC='\033[0m'
# Configuration
ADMIN_EMAIL="${1:-admin@example.com}"
WHITELIST_IP="${2:-127.0.0.1}"
# Usage
if [[ $# -gt 2 ]]; then
echo "Usage: $0 [admin_email] [whitelist_ip]"
echo "Example: $0 admin@example.com 192.168.1.0/24"
exit 1
fi
# Check if running as root/sudo
if [[ $EUID -ne 0 ]]; then
echo -e "${RED}Error: This script must be run as root or with sudo${NC}"
exit 1
fi
# Cleanup function
cleanup() {
echo -e "${RED}Error occurred. Cleaning up...${NC}"
systemctl stop apache2 httpd 2>/dev/null || true
}
trap cleanup ERR
# Auto-detect distribution
if [ -f /etc/os-release ]; then
. /etc/os-release
case "$ID" in
ubuntu|debian)
PKG_MGR="apt"
PKG_INSTALL="apt install -y"
PKG_UPDATE="apt update && apt upgrade -y"
APACHE_SERVICE="apache2"
APACHE_CONFIG_DIR="/etc/apache2"
APACHE_LOG_DIR="/var/log/apache2"
MODSEC_CONFIG="/etc/modsecurity"
ENABLE_MOD="a2enmod"
;;
almalinux|rocky|centos|rhel|ol|fedora)
PKG_MGR="dnf"
PKG_INSTALL="dnf install -y"
PKG_UPDATE="dnf update -y"
APACHE_SERVICE="httpd"
APACHE_CONFIG_DIR="/etc/httpd"
APACHE_LOG_DIR="/var/log/httpd"
MODSEC_CONFIG="/etc/httpd/modsecurity.d"
ENABLE_MOD=""
;;
amzn)
PKG_MGR="yum"
PKG_INSTALL="yum install -y"
PKG_UPDATE="yum update -y"
APACHE_SERVICE="httpd"
APACHE_CONFIG_DIR="/etc/httpd"
APACHE_LOG_DIR="/var/log/httpd"
MODSEC_CONFIG="/etc/httpd/modsecurity.d"
ENABLE_MOD=""
;;
*)
echo -e "${RED}Unsupported distro: $ID${NC}"
exit 1
;;
esac
else
echo -e "${RED}Cannot detect OS. /etc/os-release not found${NC}"
exit 1
fi
echo -e "${GREEN}Configuring Apache with DDoS protection on $PRETTY_NAME${NC}"
# Step 1: Update system packages
echo -e "${YELLOW}[1/8] Updating system packages...${NC}"
$PKG_UPDATE
# Step 2: Install Apache and security modules
echo -e "${YELLOW}[2/8] Installing Apache and security modules...${NC}"
if [[ "$PKG_MGR" == "apt" ]]; then
$PKG_INSTALL apache2 libapache2-mod-evasive libapache2-mod-security2 modsecurity-crs libapache2-mod-limitipconn
else
$PKG_INSTALL httpd mod_evasive mod_security mod_security_crs mod_limitipconn
fi
# Step 3: Install fail2ban
echo -e "${YELLOW}[3/8] Installing fail2ban...${NC}"
$PKG_INSTALL fail2ban
# Step 4: Enable Apache security modules
echo -e "${YELLOW}[4/8] Enabling Apache security modules...${NC}"
if [[ "$PKG_MGR" == "apt" ]]; then
$ENABLE_MOD evasive
$ENABLE_MOD security2
$ENABLE_MOD limitipconn
$ENABLE_MOD headers
$ENABLE_MOD rewrite
else
systemctl enable $APACHE_SERVICE
fi
# Step 5: Configure mod_evasive
echo -e "${YELLOW}[5/8] Configuring mod_evasive...${NC}"
if [[ "$PKG_MGR" == "apt" ]]; then
EVASIVE_CONFIG="$APACHE_CONFIG_DIR/mods-available/evasive.conf"
else
EVASIVE_CONFIG="$APACHE_CONFIG_DIR/conf.d/mod_evasive.conf"
fi
cat > "$EVASIVE_CONFIG" << EOF
<IfModule mod_evasive24.c>
DOSHashTableSize 512
DOSPageCount 3
DOSPageInterval 1
DOSSiteCount 50
DOSSiteInterval 1
DOSBlockingPeriod 600
DOSLogDir "$APACHE_LOG_DIR"
DOSEmailNotify $ADMIN_EMAIL
DOSWhitelist $WHITELIST_IP
</IfModule>
EOF
chown root:root "$EVASIVE_CONFIG"
chmod 644 "$EVASIVE_CONFIG"
# Step 6: Configure mod_security
echo -e "${YELLOW}[6/8] Configuring mod_security...${NC}"
if [[ "$PKG_MGR" == "apt" ]]; then
cp /etc/modsecurity/modsecurity.conf-recommended /etc/modsecurity/modsecurity.conf
sed -i 's/SecRuleEngine DetectionOnly/SecRuleEngine On/' /etc/modsecurity/modsecurity.conf
sed -i 's/SecAuditLogParts ABIJDEFHZ/SecAuditLogParts ABCEFHJKZ/' /etc/modsecurity/modsecurity.conf
else
mkdir -p "$MODSEC_CONFIG"
cp /etc/httpd/modsecurity.d/modsecurity.conf-recommended /etc/httpd/modsecurity.d/modsecurity.conf 2>/dev/null || true
sed -i 's/SecRuleEngine DetectionOnly/SecRuleEngine On/' /etc/httpd/modsecurity.d/modsecurity.conf 2>/dev/null || true
sed -i 's/SecAuditLogParts ABIJDEFHZ/SecAuditLogParts ABCEFHJKZ/' /etc/httpd/modsecurity.d/modsecurity.conf 2>/dev/null || true
fi
# Step 7: Create Apache security configuration
echo -e "${YELLOW}[7/8] Creating Apache security configuration...${NC}"
if [[ "$PKG_MGR" == "apt" ]]; then
SECURITY_CONF="$APACHE_CONFIG_DIR/conf-available/security-hardening.conf"
mkdir -p "$(dirname "$SECURITY_CONF")"
else
SECURITY_CONF="$APACHE_CONFIG_DIR/conf.d/security-hardening.conf"
fi
cat > "$SECURITY_CONF" << EOF
# Security Headers
Header always set X-Content-Type-Options nosniff
Header always set X-Frame-Options DENY
Header always set X-XSS-Protection "1; mode=block"
Header always set Strict-Transport-Security "max-age=63072000; includeSubDomains; preload"
# Hide Apache version
ServerTokens Prod
ServerSignature Off
# Connection limiting
<IfModule mod_limitipconn.c>
MaxConnPerIP 10
</IfModule>
# Basic rate limiting
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteMap requests txt:$APACHE_LOG_DIR/requests.map
RewriteCond \${requests:\%{REMOTE_ADDR}|0} >20
RewriteRule ^(.*)$ - [F,L]
</IfModule>
EOF
chown root:root "$SECURITY_CONF"
chmod 644 "$SECURITY_CONF"
if [[ "$PKG_MGR" == "apt" ]]; then
a2enconf security-hardening
fi
# Configure fail2ban
cat > /etc/fail2ban/jail.local << EOF
[DEFAULT]
bantime = 3600
findtime = 600
maxretry = 5
[apache-auth]
enabled = true
port = http,https
logpath = $APACHE_LOG_DIR/error.log
[apache-badbots]
enabled = true
port = http,https
logpath = $APACHE_LOG_DIR/access.log
[apache-noscript]
enabled = true
port = http,https
logpath = $APACHE_LOG_DIR/access.log
[apache-overflows]
enabled = true
port = http,https
logpath = $APACHE_LOG_DIR/error.log
EOF
# Step 8: Start and enable services
echo -e "${YELLOW}[8/8] Starting and enabling services...${NC}"
systemctl enable $APACHE_SERVICE
systemctl enable fail2ban
# Create log directory if it doesn't exist
mkdir -p "$APACHE_LOG_DIR"
chown www-data:www-data "$APACHE_LOG_DIR" 2>/dev/null || chown apache:apache "$APACHE_LOG_DIR" 2>/dev/null || true
# Test Apache configuration
if ! $APACHE_SERVICE -t 2>/dev/null && ! httpd -t 2>/dev/null; then
echo -e "${RED}Apache configuration test failed${NC}"
exit 1
fi
systemctl restart $APACHE_SERVICE
systemctl restart fail2ban
# Verification
echo -e "${GREEN}Verifying installation...${NC}"
if systemctl is-active --quiet $APACHE_SERVICE; then
echo -e "${GREEN}✓ Apache is running${NC}"
else
echo -e "${RED}✗ Apache is not running${NC}"
fi
if systemctl is-active --quiet fail2ban; then
echo -e "${GREEN}✓ Fail2ban is running${NC}"
else
echo -e "${RED}✗ Fail2ban is not running${NC}"
fi
echo -e "${GREEN}Apache DDoS protection configuration complete!${NC}"
echo -e "${YELLOW}Configuration details:${NC}"
echo "- Admin email: $ADMIN_EMAIL"
echo "- Whitelisted IP: $WHITELIST_IP"
echo "- Apache service: $APACHE_SERVICE"
echo "- Log directory: $APACHE_LOG_DIR"
echo ""
echo -e "${YELLOW}To test the configuration:${NC}"
echo "sudo $APACHE_SERVICE -t"
echo "sudo fail2ban-client status"
Review the script before running. Execute with: bash install.sh