Block User-Agent in htaccess for Apache Webserver

This guide will show you how to block requests to your site if they come with a certain User-Agent. This can be very useful to fend of a WordPress pingback DDoS attack or block other unwanted requests.

Assuming .htaccess is already enabled on your server (it is on most servers running Apache), add the following near the very top to block this user-agent from accessing your site.

$ cat .htaccess
<IfModule mod_rewrite.c>
  RewriteEngine On
  RewriteCond %{HTTP_USER_AGENT} ^WordPress [NC]
  RewriteRule .* - [F,L]
</IfModule>

The example above will block any request that has a User-Agent that starts with (the ^ regex modifier) “WordPress”. I used this particular example to defend against a WordPress pingback attack, where old versions of WordPress are tricked into attacking a single target.

If you want to block multiple User-Agents in htaccess, you can combine them into a single line like this.

$ cat .htaccess
<IfModule mod_rewrite.c>
  RewriteEngine On
  RewriteCond %{HTTP_USER_AGENT} ^(WordPress|ApacheBench) [NC]
  RewriteRule .* - [F,L]
</IfModule>

The example above blocks all requests with a User-Agent that starts with WordPress or ApacheBench .

Alternatively, you can use a SetEnvIfNoCase block, which sets an environment variable if the condition described is met. This can be useful if, for some reason, mod_rewrite isn’t available.

$ cat .htaccess
<IfModule mod_setenvif.c>
  SetEnvIfNoCase User-Agent (sqlmap|wordpress|apachebench) bad_user_agents

  <RequireAll>
    Require all granted
    Require not env bad_user_agents
  </RequireAll>
</IfModule>

The example above will deny access to everyone that has a User-Agent that has either SQLMap , WordPress or ApacheBench in the string. It’s case insensitive and the User-Agent does not have to start with that string, because it lacks the ^ modifier.

(The original version of this post used the old Order Allow,Deny / Deny from env= syntax. That’s the mod_access_compat form from Apache 2.2 and it’s deprecated in Apache 2.4 ; use the Require directives above instead.)