Block User-Agent in htaccess for Apache Webserver

Mattias Geniar, Sunday, August 9, 2015

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]

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]

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

  Order Allow,Deny
  Allow from all
  Deny from env=bad_user_agents

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.

Hi! My name is Mattias Geniar. I'm a Support Manager at Nucleus Hosting in Belgium, a general web geek & public speaker. Currently working on DNS Spy & Oh Dear!. Follow me on Twitter as @mattiasgeniar.

Share this post

Did you like this post? Will you help me share it on social media? Thanks!


Alex Monday, December 21, 2015 at 02:09 - Reply

Thank you so much! Great way to handle the attack.


Oliver Wednesday, October 12, 2016 at 13:44 - Reply

I am confused about the syntax

Some examples I could find are:

SetEnvIfNoCase User-Agent "Whacker" bad_bot
SetEnvIfNoCase User-Agent "^Widow" bad_bot

a) Why do people sometimes add ^ and sometimes they don’t?

b) sometimes i see SetEnvIfNoCase User-Agent “^Widow.*” bad_bot´
What effect has it if I add .*



Mattias Geniar Thursday, October 13, 2016 at 11:37 - Reply

Hi Oliver,

Those are regular expression “special characters”, you can test the results here;

Leave a Reply

Your email address will not be published. Required fields are marked *

Inbound links