Using htaccess to Restrict File Access by IP Address

Every so often there’s a new exploit targeted. This shows as an increase in the rate against a particular file.

For example some time ago there were lots of attempts trying to access to the file upload.php in either themes or plug-ins.

This reflects a vulnerability in an inclusion within a number of themes.

With the aim that only authorised users and IP address shall be looking to upload content I looked towards using the .htaccess file to add the restriction.

The .htaccess file is located in the root of the website. It allows local configuration overrides of the Apache web server.

Blocking access by IP Address

Access is restricted using the old favourite of deny and allow.

For example to only allow access from the IP address of 192.0.2.52.

Order Deny, Allow
Deny from all
Allow from 192.0.2.52

Here we first set the access rule order to be deny, then allow.

Where the order defines the sequence in which the deny and allow rules are processed.

The actual order in which the rules are presented within the .htaccess file doesn’t matter. Based upon the order either the deny rules will be processed first or the allow ones.

Beware – if the order in the above were set to Order Allow, Deny, the result would be to prevent access to all. The single address would be allowed, followed by all attempts at access being denied.

The restriction can be further adapted to incorporate the files structure. Either individual files or directories.

<Files /index.php>
Order Deny,Allow
Deny from all
Allow from 192.0.2.52
</Files>

In the above example a specific file is entered. The index.php file in the root of the website.

An alternative is a match, without the directory structure, with the simple name of the file.

This is the form which we will use, replacing /index.php with upload.php. It will then be restricted in whatever directory it is found, accounting for the potential themes and plug-ins.

<Files upload.php>
Order Deny,Allow
Deny from all
Allow from 192.0.2.52
</Files>

Pattern matching, which follows the regular expressions may be used. For example to prevent access to certain file types:

<Files ~ “.(inc|zip|rar)$”>

Here I’ve prevented access to compressed files and includes.

When matching multiple files FilesMatch is used in preference to Files. Although either may be used, its easy to read and gather the implication of the code within the .htaccess file where FilesMatch is showing an expectation of multiple matches, as opposed to the single file.