Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Space character not being matched by regex in .htaccess

I want to block any request that contains an ID that contains any non-numeric character using mod_rewite, or an empty ID. I have the following rule in my .htaccess file:

RewriteCond %{QUERY_STRING} ID=(\d*[^\d&]+\d*)*(&|$)
RewriteRule .* - [F]

Which is working except for requests that contain a space character eg.

GET /page.php?ID=5 5 HTTP/1.1

The space character between the two 5s is successfully matched by [^\d&]+ when I use various test suites (such as https://regex101.com/) but this type of request is still getting through.

What do I need to change?

(yes, incorrect user input is handled in my PHP so it doesn't matter if this gets through)

like image 991
Orinoco Avatar asked Dec 08 '25 10:12

Orinoco


1 Answers

Perhaps this will work for you:

RewriteCond %{QUERY_STRING} !(?:^|&)ID=\d+(?:&|$)
RewriteRule ^ - [F]

And if you only want it to affect requests that do have an ID parameter in the query string (so requests with no ID are allowed):

RewriteCond %{QUERY_STRING} (?:^|&)(?:\%(?:20|09))*ID(?:\%(?:20|09))*= [NC]
RewriteCond %{QUERY_STRING} !(?:^|&)ID=\d+(?:&|$)
RewriteRule ^ - [F]

I also added [NC] (non-case-sensitive) so that iD etc. will also be covered by this.


Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!