Custom Rules
Learning Focus
By the end of this lesson you will understand how to write simple custom ModSecurity rules for application-specific protection.
When to Write Custom Rules
Custom rules fill gaps that the OWASP CRS does not cover:
- Blocking specific bot user agents
- Restricting access to admin APIs
- Blocking known-bad IP patterns
- Application-specific input validation
Example Rules
Block a Specific User Agent
SecRule REQUEST_HEADERS:User-Agent "BadBot" "id:10001,phase:1,deny,status:403,msg:'Blocked bad bot'"
Block Access to Sensitive Paths
SecRule REQUEST_URI "/\.env" "id:10002,phase:1,deny,status:403,msg:'Blocked .env access'"
SecRule REQUEST_URI "/\.git" "id:10003,phase:1,deny,status:403,msg:'Blocked .git access'"
Rate Limit Login Attempts
SecRule REQUEST_URI "/wp-login.php" "id:10004,phase:1,pass,nolog,setvar:ip.login_count=+1"
SecRule IP:LOGIN_COUNT "@gt 10" "id:10005,phase:1,deny,status:429,msg:'Too many login attempts'"
Best Practices
| Practice | Why |
|---|---|
| Use unique rule IDs (10000+) | Avoid conflicts with OWASP CRS |
| Test in detection mode first | Prevent blocking legitimate users |
| Log before blocking | Understand what the rule catches |
| Keep rules simple | Complex rules are hard to debug |
Key Takeaways
- Custom rules extend WAF protection for application-specific needs.
- Always assign unique IDs above 10000 to avoid CRS conflicts.
- Test in detection mode before enabling blocking.
What's Next
- Return to the Security module for the complete overview.