I would like to block all requests starting with /search?q=
as they generate unwanted load on my server.
Following this question https://stackoverflow.com/questions/4640807/how-to-block-bot-requests-to-urls-that-match-a-common-pattern-in-apache , I tried the following code:
<Location />
RewriteEngine On
RewriteCond %{REQUEST_URI} ^/search?q=[^/] [NC]
RewriteRule ^.*$ - [F,L]
</Location>
but it's blocking way too many URLs (like everything starting with search)
I tried different variations but they didn't work. What would be the correct syntax?
The code you posted won't do that? In fact, the code you posted is unlikely to block anything, unless there was a URL encoded
?
(ie.%3F
) in the original request URL?However, in order to match the query string (ie.
q=
) then you need to match against theQUERY_STRING
server variable. TheREQUEST_URI
Apache server variable contains the URL-path only (no query string).So, in order to block all requests that start
/search?q=
then you would need something like the following:This ensures that the URL-path matches
/search
and the query string startsq=
.The
NC
flag is not required unless you need to also matchQ=
in the query string.The
L
flag is not required with theF
flag as it is implied.That's probably your problem. The mod_rewrite directives in the server config are overridden by the virtual host by default and effectively ignored. The vHosts won't inherit the mod_rewrite directives from the server config unless you specifically enable mod_rewrite inheritance, which you would ordinarily do from the vhost container. However, on Apache 2.4.8+ you can do this in the main server config (server context). For example:
InheritDownBefore
ensures that the directives in the server config are executed before the directives in the vhost.