Flash Sale:75% Off Hosting + Free DomainEnds in13h47m14sView Plans
Hostvento logoHostvento

How to Write Your Own WAF Rules

This guide shows how to add a custom rule to a ModSecurity firewall, so you can block a pattern that the standard rules miss.

Firewall2 min read7 steps

What is a custom WAF rule?

A WAF is a Web Application Firewall. A firewall is a guard that checks traffic. The standard rule sets cover many attacks. A custom rule is one you write yourself. It is like adding your own line to the guard's notebook: "If anyone asks for this strange page, say no."

Examples: block a certain bad URL, block one user agent, or protect an admin page.

This guide uses ModSecurity, the most common WAF engine on hosting servers. Writing rules needs root access on a VPS or dedicated server. On shared hosting, ask Hostvento support whether custom rules are possible.

The parts of a rule

A ModSecurity rule is written with SecRule. It has three parts:

  • Variable: what to look at, such as the web address.
  • Operator: how to compare, such as "contains".
  • Actions: what to do, such as deny and log.

Steps

  1. Take a backup of your current ModSecurity configuration.
  2. In WHM, search for ModSecurity Tools or ModSecurity Configuration. On a plain server, find your custom rules file. On cPanel servers, it is often /etc/apache2/conf.d/modsec/modsec2.user.conf.
  3. Open the file with an editor.
  4. Add a rule. This example blocks any request to a page with wp-config.bak in the address:
SecRule REQUEST_URI "@contains wp-config.bak" \
  "id:1000001,phase:1,deny,status:403,log,msg:'Blocked backup file request'"

It says: if the address contains that name, refuse the request with a 403 error and write a log line.

  1. Give every rule a unique id. Use numbers like 1000001 to avoid clashing with others.
  2. Save the file.
  3. Test the web server settings, then restart it. On many servers:
apachectl configtest

This checks your settings for typos. Restart only if it says Syntax OK.

Another example

Block a bad user agent called BadBot:

SecRule REQUEST_HEADERS:User-Agent "@contains BadBot" \
  "id:1000002,phase:1,deny,status:403,log,msg:'Bad bot blocked'"

Test it

Visit the blocked address in your browser. You should get a 403 error. Check the ModSecurity log for your message.

Warning: A rule that is too wide can block real visitors. Test on one site first. Start with log only, without deny, to see what it would block.

Need help? Open a support ticket.

Quick recap

  • A custom rule blocks a pattern you choose.
  • Use SecRule with a variable, operator and actions.
  • Give each rule a unique id.
  • Run apachectl configtest before restarting.
  • Test and read the log.