Protecting Nginx with a ModSecurity Web Application Firewall (WAF)
This article explains why web applications need a Web Application Firewall, introduces ModSecurity as a WAF for Nginx, and provides step‑by‑step installation, configuration, custom rule creation, and service restart commands to defend against attacks such as SQL injection and XSS.
With the rapid growth of the Internet, web applications have become essential, but they are exposed to attacks such as SQL injection and XSS.
A Web Application Firewall (WAF) monitors and filters HTTP traffic using patterns, rule engines, and signatures to block malicious requests.
Deploying a WAF with Nginx improves security; this article demonstrates using the ModSecurity module.
Installation: sudo apt-get install libmodsecurity3 libmodsecurity-dev
Configuration: add to the Nginx server block
<code>location / {
# Include ModSecurity configuration file
ModSecurityEnabled on;
ModSecurityConfig /etc/nginx/modsec/modsecurity.conf;
}</code>Create a custom rule file, e.g., sudo nano /etc/nginx/modsec/modsecurity_custom_rules.conf , and add a rule to block SQL injection:
<code>SecRuleEngine On
# Prevent SQL injection
SecRule ARGS "@rx (select|union|insert|update|drop|delete)" "id:1,deny,status:403,msg:'SQL Injection attempt'"</code>After editing, restart Nginx: sudo systemctl restart nginx
The WAF now protects the web application, and administrators can choose other modules such as OpenResty while tailoring rules to their environment.
php中文网 Courses
php中文网's platform for the latest courses and technical articles, helping PHP learners advance quickly.
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.