• caglararli@hotmail.com
  • 05386281520

How to set requests rate limit using Mod Security Rule?

Çağlar Arlı      -    20 Views

How to set requests rate limit using Mod Security Rule?

I tried to find a way to limit requests per minute (or other time) using mod security rule in apache, but didn't get success from anywhere.

I think it needs more expertise to write such complex rules in mod security.

Our need is to setup rate limit per website (vhost) per ip, per minute(other time).

I am trying to setup a collection of combination of IP,Hostname and its counter initially set to 0

When request comes , if it is not internal request (same website as referrer) , consider it as a request to consider and increment that counter, if it counter reaches the limit, it should give 429-too many requests, after that specified period (say 1 minute) , that ip can request successfully again.

Something I tried as below, but didn't get success.

SecAction "id:4001,phase:1,nolog,pass,initcol:%{SERVER_NAME}/ip=%{REMOTE_ADDR}/count/0,expirevar:%{SERVER_NAME}/ip=%{REMOTE_ADDR}/count=60"

# Skip internal requests with matching referer hostname (optional)
SecRule REQUEST_HEADERS:Referer "^https?://%{HTTP_HOST}/" "id:4002,phase:1,chain,skipAfter:4004,msg:'Internal Request'"

# Count request for external requests (corrected rule)
SecRule IP: %{SERVER_NAME}/ip "@rx ^" phase:1, chain|nolog, t:none "setvar:ip=%{SERVER_NAME}/ip.%{REMOTE_ADDR}/count+=1"

# Block requests exceeding limit (adjust threshold as needed)
SecRule "phase:1,id:4004,chain,deny,status:429,log,msg:'Rate limit exceeded for IP'" "expr: %{tx.vars.ip.%{SERVER_NAME}/ip.%{REMOTE_ADDR}/count} gt 50"  # Adjust limit (here 50)