htaccess mod_rewrite for specific starting substrings only

jammy-d0dger
jammy-d0dger used Ask the Experts™
on
OK, when reading this question please ignore the fact that the developers should be fixing their out of date plugins... this is another battle being fought elsewhere.

We are trying to block querystrings in the format of mydomainname.com/?q=anytexthere

I have successfully used this code in the htaccess file:

RewriteCond %{QUERY_STRING} \bq=\b [NC]
RewriteRule ^ - [F]

Open in new window


But this unfortunately stops timthumb.php requests from working, I assume because the timthumb string includes ;q=21 (for example).

So, given that we only want to block requests that start with /?q=anytexthere how would we modify the RewriteCond ?

Help appreciated.
Comment
Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®

Commented:
What's wrong with:
RewriteCond %{QUERY_STRING} \bq=anytexthere\b [NC]
RewriteRule ^ - [F]

Open in new window


HTH,
Dan

Author

Commented:
Thanks Dan,

Well, as mentioned in the question, this unfortunately stops timthumb requests from working because timthumb requests also have a parameter in the querystring of "q=".   However, in timthumb the q= parameter is always at the end of the querystring, but the exploit we want to stop, always has just a q= parameter on it's own, straight after the '?'

i.e. http://mydomainname.com/about/?q=hot_online_poker

So, my original code snippet works and does block these exploit links being used but it also blocks timthumb requests such as:

/timthumb.php?src=http://mydomainname.com/wp-content/uploads/2015/04/my-special-image-980x2100.jpg&w=980&h=212&q=90

...because of the q=90 on the end.

Hope that makes sense.

Commented:
OK. Then how about any text not starting with a number?
RewriteCond %{QUERY_STRING} \bq=[a-zA-Z][0-9a-zA-Z]*$ [NC]
RewriteRule ^ - [F]

Open in new window

PMI ACP® Project Management

Prepare for the PMI Agile Certified Practitioner (PMI-ACP)® exam, which formally recognizes your knowledge of agile principles and your skill with agile techniques.

Author

Commented:
Ah Dan... that works a treat.  Can I include empty parameter in that too, i.e. ?q= with nothing after it, (currently this is not caught and get's through to the exploit).
Commented:
Use an OR:
RewriteCond %{QUERY_STRING} \bq=$ [NC,OR]
RewriteCond %{QUERY_STRING} \bq=[a-zA-Z][0-9a-zA-Z]*$ [NC]
RewriteRule ^ - [F]

Open in new window

Author

Commented:
And that right there, is a solution.  Many thanks Dan.

Commented:
You're welcome.

Glad I could help!

Do more with

Expert Office
Submit tech questions to Ask the Experts™ at any time to receive solutions, advice, and new ideas from leading industry professionals.

Start 7-Day Free Trial