Preventing Direct File Access Using a .htaccess File
Preventing a user or bot from directly accessing files within a directory can be a very useful trick, especially when the files in question contain sensitive information or when a user must pay for the file prior to getting access.
Deny access to everyone
To protect your files you must first ensure that they are all within the same directory. If we had a bunch of downloadable ebooks that needed to be purchased prior to viewing, for example, we would place them in a folder called ‘ebooks’. Then simply place a .htaccess file within this ‘ebooks’ directory along with the files in question that contains the following text:
deny from all
Simple huh? But what if we want to allow or deny access to only certain IP addresses…
Deny access to everyone, except specific IP addresses
To only allow certain IP addresses direct access to files within a directory you should follow the steps as outlined above but place the following text within your .htaccess file instead:
order deny, allow deny from all allow from 111.222.333.444
Simply replace 111.222.333.444 for the IP address that you want to grant access to.
Deny access to only specific IP addresses
If it’s only a specific user or bot that you want to prevent having access to your files, simply follow the instructions above but update your .htaccess file like so:
order allow, deny deny from 111.222.333.444 allow from all
In the above example 111.222.333.444 is the IP address that we want to block from reading the files directly.