Mod security is a free Web Application Firewall (WAF) that works with Apache, Nginx and IIS.
It supports a flexible rule engine to perform simple and complex operations and comes with a Core Rule Set (CRS) which has rules for SQL injection, cross site scripting, Trojans, bad user agents, session hijacking and a lot of other exploits.
Excluding Hosts and Directories
Writing Your Own mod_security Rules