How to Block User Agent in Apache using .htaccess


block http user agent htaccess

Sometimes, you may need to block specific user agents from your website, to thwart DDOS attacks or unwanted requests. Here’s how to block user agent in Apache using .htaccess.

 

How to Block User Agent in Apache using .htaccess

Here’s how to block user agent in Apache using .htaccess. Before proceeding, please ensure that you have enabled .htaccess file in your Apache server. Here are the steps to do it:

 

Place your .htaccess file in the root document folder of your website (/var/www/html).

 

1. Open .htaccess file

Open .htaccess file in a text editor.


$ sudo vim /var/www/html/.htaccess

 

2. Block unwanted user agents

Let’s say you want to block User agent “WordPress” from your site. Simply add the following code to your .htaccess file.


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

The above code will check the HTTP_USER_AGENT for value “WordPress” and if it is present, give “403: Access forbidden” response. Since we use regex operator (^) it will do a case insensitive match. So it will block any visitor with a user agent starting from “WordPress”

If you want to block multiple user agents, use the ‘|’ operator.


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

 

The above code will block visitors with user agent starting from WordPress or ApacheBench

 

3. Restart Apache web server

Restart Apache web server to apply changes


$ sudo /etc/init.d/apache2 start [Debian or Ubuntu]
# sudo apachectl restart [RHEL, CentOS or Fedora]

 

 

 

About Sreeram Sreenivasan

Sreeram Sreenivasan is the Founder of Ubiq, a business dashboard & reporting platform for small & medium businesses. Ubiq makes it easy to build business dashboards & reports for your business. Try it for free today!