Setting Up ModSecurity as a Web Application Firewall for Apache2

ModSecurity turns Apache into a genuine Web Application Firewall, inspecting requests against a ruleset before they ever reach your application — a real additional layer of defense beyond application-level input validation.

sudo apt install libapache2-mod-security2

# Enable it, and switch from detection-only to blocking mode
sudo cp /etc/modsecurity/modsecurity.conf-recommended /etc/modsecurity/modsecurity.conf
sudo sed -i 's/SecRuleEngine DetectionOnly/SecRuleEngine On/' /etc/modsecurity/modsecurity.conf

sudo a2enmod security2
sudo systemctl restart apache2

The OWASP Core Rule Set

sudo apt install modsecurity-crs
# Link it into the mod_security config to enable a comprehensive,
# actively-maintained set of attack signatures (SQLi, XSS, and more)

Start in Detection Mode

Always run ModSecurity in DetectionOnly mode for at least a few days on a new site before switching to blocking — the OWASP Core Rule Set is thorough enough that it will generate false positives against legitimate traffic patterns specific to your application, and you want to tune those out before it starts actively rejecting real users.