Search code examples
regexapache.htaccesswebserver

Apache - block request but only when three keywords are not present in the query string


I need to return 403 for any GET request that contains example select, md5, declare, drop and similar, but only when following three keywords are not present in QUERY_STRING (key1, key2 and keyx).

Current situation (it works fine if either: name or type or value does not exist in query string):

RewriteCond %{QUERY_STRING} !(^|&)/key1|key2|keyx/($|&) 
RewriteCond %{QUERY_STRING} ^.*(phpunit|md5|benchmark|union|cast|declare|drop).* [NC]

Basically all I need is to bypass the rule on second line when there are all three keywords present in query string.


Solution

  • You may use these 2 conditions:

    RewriteCond %{QUERY_STRING} !(^|&)(key1|key2|keyx)\b [NC]
    RewriteCond %{QUERY_STRING} \b(phpunit|md5|benchmark|union|cast|declare|drop)\b [NC]
    
    • \b is for word boundary
    • mod_rewrite patterns don't allow /.../ notation like Javascript
    • grouping was wrong in your attempt
    • There is no need to match .* before and after keywords