Avatar of jammy-d0dger
jammy-d0dger
 asked on

htaccess mod_rewrite for specific starting substrings only

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.
WordPressPHP

Avatar of undefined
Last Comment
Dan Craciun

8/22/2022 - Mon
Dan Craciun

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

Open in new window


HTH,
Dan
jammy-d0dger

ASKER
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.
Dan Craciun

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

I started with Experts Exchange in 2004 and it's been a mainstay of my professional computing life since. It helped me launch a career as a programmer / Oracle data analyst
William Peck
jammy-d0dger

ASKER
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).
ASKER CERTIFIED SOLUTION
Dan Craciun

THIS SOLUTION ONLY AVAILABLE TO MEMBERS.
View this solution by signing up for a free trial.
Members can start a 7-Day free trial and enjoy unlimited access to the platform.
See Pricing Options
Start Free Trial
GET A PERSONALIZED SOLUTION
Ask your own question & get feedback from real experts
Find out why thousands trust the EE community with their toughest problems.
jammy-d0dger

ASKER
And that right there, is a solution.  Many thanks Dan.
Dan Craciun

You're welcome.

Glad I could help!
⚡ FREE TRIAL OFFER
Try out a week of full access for free.
Find out why thousands trust the EE community with their toughest problems.