Blocking Unwanted Traffic Using .htaccess

All of the recipes below refer to an .htaccess file. An .htaccess file is a text file named ".htaccess" placed in your www/ directory or any subdirectory thereof, with web user-readable (0644) permissions.

The .htaccess file contains rules which apply to the handling of traffic to the directory containing the .htaccess file, and all subdirectories thereof. So for example, if you had a rule you wanted to apply to your entire site, you would put an .htaccess file in your www/ directory. If you wanted the rule to apply only to your www/mystuff/ directory, you would place the .htaccess file in www/mystuff/.

You may already have an .htaccess file in your directory if you are using File Manager or FrontPage or other web editor. You may add additional rules to an existing .htaccess file, but you should make a backup of the existing file just in case.

Adding or changing .htaccess files may affect the functioning of the entire site, so please test any edits thoroughly and consider testing them in an test subdirectory before applying them to your entire site.


How do I deny traffic from a particular IP address?

Suppose you want to block traffic from IP address 192.168.1.80.

Add to your .htaccess file the following line:

deny from 192.168.1.80

You can block entire networks using the same type of rule. To block the entire network 192.168.1.0-192.168.1.255:

deny from 192.168.1

You can use multiple lines, one for each network or host:

deny from 192.168.1
deny from 192.168.3.24
deny from 192.168.5.33

See also Apache's mod_access page


How do I block traffic from a particular referrer?

You may want to block traffic from particular sites that link to your site. You can perform HTTP referrer-based blocking using mod_rewrite.

Suppose you would like to block (with a 403 Forbidden code) traffic referred by badguys.com. Add the lines to .htaccess:

RewriteEngine on
RewriteCond %{HTTP_REFERER} ^http://(www\.)?badguys\.com [NC]
RewriteRule (.*) - [F]

You can block multiple domains using multiple RewriteCond lines and the [OR] flag, as follows:

RewriteEngine on
RewriteCond %{HTTP_REFERER} ^http://(www\.)?badguys\.com [NC,OR]
RewriteCond %{HTTP_REFERER} ^http://(www\.)?badreferrers\.com [NC]
RewriteRule (.*) - [F]

NB: Be sure to add [OR], as shown, to each RewriteCond line but the last. The default behavior is a logical AND, i.e. the RewriteRule takes effect only if all of the RewriteCond lines apply, which you do not want here.

See also Apache's mod_rewrite page