Protect Downloadable Files with .htaccess Rules
Looking for a way to protect your digital downloads? The question frequently asked by digital authors, "How do I keep users from finding out my file URL and just downloading without license or permission?" This can, in fact, be a very real problem! Through a little .htaccess magic, we can lock down your pdfs or mp3s (or whatever your file extension might be). Once locked down, only your scripts have the ability to deliver the file to the users browser.
If you are unfamiliar with .htaccess files, they are "distributed configuration files" used by Apache. They are extremely powerful in that they allow you to change configurations for your site on a per-directory basis.
In this tutorial, we are going to create a way to protect our ebook that we have just finished authoring. It is available in the format of a .pdf file, htaccesspower.pdf.
To get our scenario setup, let's create a directory on our server, /downloads/. In this directory, we are going to place our protected file, htaccesspower.pdf, resulting in a file located at http://www.myserver.com/downloads/htaccesspower.pdf. Now it goes without saying that, in its current state, this file is completely unprotected. If a user found out this URL, they could just point their web browser to it and download our ebook without us having any control whatsoever. Even worse, it could become victim to hot linking.
Now, in our /downloads/ directory, we need to create an .htaccess file. In your text editor, open the file and add the following code:
<Files htaccesspower.pdf>
order allow,deny
deny from all
</Files>
In this case, we are explicitly defining the one file that we want to protect. However, you may run into cases where you want to protect all files of a particular extension or multiple file types. Say, for instance, we created an audiobook version of our ebook saved as an mp3, htaccesspower.mp3. In this case, we would use regular expressions to match all files with the correct file extension and deny access.
Here's what your .htaccess file should look like:
<FilesMatch ".(pdf|mp3)$">
Order Allow,Deny
Deny from all
</FilesMatch>
To quickly breakdown the regular expression in the code above, we are simply stating that we want to apply the rule to .pdf's or .mp3's. Say you added an htaccesspower.avi that was to be protect as well, here's what the new code would look like:
<FilesMatch ".(pdf|mp3|avi)$">
Order Allow,Deny
Deny from all
</FilesMatch>
Now your files are locked down! No longer will people be able to download your hard work directly without you first deciding to serve the download to them!
At this point, your question might be, "How do I make it so people can actually download the files?" If this is the case, read the tutorial, Using PHP Headers to Force Download


