Preventing access to specific file extensions using .htaccess

Wednesday 13th May 2009 at 11:35 pm

Suppose you’re building a website where visitors are required to upload personal documents such as a CV or anything else with personal details. There are several ways you can protect these files from being downloaded by unauthorized users on a Unix server.

Three popular approaches are:

1. Store the files below the web-accessible directory.
2. Use permissions to limit who can access the files.
3. Use a .htaccess file to restrict access to a directory or file types.

In this article we will discuss the third option, using .htaccess.

What is .htaccess?

In Unix files starting with a ‘.’ are special. They are hidden files and the .htaccess file is one such example. In the last couple of years this file has risen in profile thanks to the popularity of Apache URL rewriting for SEO and presentation purposes. The .htaccess file is a powerful tool when used correctly.

Preventing access to specific file types

Suppose you are allowing user’s to upload cv’s in either .pdf or .doc format. You don’t have to lock client’s browsers out of the directory they’re stored in completely, you can use .htaccess to only forbid access to only the necessary file types.

First create a file in the directory you plan to store the files in called “.htaccess”. Then, place the following into the file:

<FilesMatch ".(pdf|doc)$">
Order Allow,Deny
Deny from all
</FilesMatch>

It’s as simple as that!

Accessing the file content

It’s possible to enable an authorised user to access the file using a simple PHP script.

Use file_get_contents(‘path/to/file’); to retrieve the file contents, then pass appropriate headers using header(); to allow the download.