Block User-Agent in htaccess for Apache Webserver

Want to help support this blog? Try out Oh Dear, the best all-in-one monitoring tool for your entire website, co-founded by me (the guy that wrote this blogpost). Start with a 10-day trial, no strings attached.

We offer uptime monitoring, SSL checks, broken links checking, performance & cronjob monitoring, branded status pages & so much more. Try us out today!

Profile image of Mattias Geniar

Mattias Geniar, August 09, 2015

Follow me on Twitter as @mattiasgeniar

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

  Order Allow,Deny
  Allow from all
  Deny from env=bad_user_agents
</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.



Want to subscribe to the cron.weekly newsletter?

I write a weekly-ish newsletter on Linux, open source & webdevelopment called cron.weekly.

It features the latest news, guides & tutorials and new open source projects. You can sign up via email below.

No spam. Just some good, practical Linux & open source content.