Search code examples
htmlwordpressapache.htaccess

Block all search queries except on .htaccess


i am currently working on a wordpress website in which I've a special case. I want one specific search query to be allowed while rejecting all others.

For example:

  • www.example.com - PASS
  • www.example.com/page - PASS
  • www.example.com
  • www.example.com/?myQuery - PASS
  • www.example.com/?anyotherQuery - 404

Right now, I have tried it using the following re-write rule but it is also blocking access to other pages.

RewriteBase "/"
RewriteCond %{QUERY_STRING} ! myQuery
RewriteRule ^.* - [F]`

I'm new in rewrite and htaccess thing so need help in achieving this.


Solution

  • Try the following, at the top of your .htaccess file, before the WordPress front-controller.

    RewriteCond %{QUERY_STRING} .
    RewriteCond %{QUERY_STRING} !=myQuery
    RewriteRule ^ - [F]
    

    The above states... for any URL that contains a query string (first condition) and the query string is not exactly myQuery (second condition) then respond with a 403 Forbidden (Apache response, not WordPress).

    The = prefix on the CondPattern makes it a lexicographical string comparison (not a regex) and the ! prefix negates the result.

    RewriteBase "/"
    RewriteCond %{QUERY_STRING} ! myQuery
    RewriteRule ^.* - [F]`
    

    The RewriteBase directive is irrelevant here. The space between ! and myQuery is erroneous. But this would potentially block anything where the query string does not contain myQuery, including when there is no query string at all.