I recently wanted to protect some files from unauthorised download on a WordPress site, but still allow authorised users to easily access to the files.
The simplest solution I found was to put the files in custom directory, place the links to the files on a WordPress password protected page, and use a .htaccess file to limit access to the files to users who are logged in. This rather simple approach works rather well if you take a little care with the directory and/or file naming.
Here is the step-by-step guide.
1. Make a new directory on your site and upload the files you want to protect to this directory (using ftp or scp). Make sure you chose a directory name that is hard to guess. I would recommend a random string — something like “vg4thbspthdbd8th” — just don’t use this exact string!
mkdir /path_to_protected_directory/
2. ssh into the server and and create a .htaccess file in the protected directory using nano.
sudo nano /path_to_protected_directory/.htaccess
3. Copy and paste the following text into the .htaccess file.
Options -Indexes php_flag engine off RewriteEngine on RewriteCond %{HTTP_REFERER} !^http(s)?://(www\.)?yourwebsite.com [NC] RewriteCond %{HTTP_COOKIE} !^.*wp-postpass.*$ [NC] RewriteRule \.(zip|rar|exe|gz)$ - [NC,F,L]
4. Change the yourwebsite.com to your website’s actual name. You should also change the RewriteRule line to suit the content you wish to protect. Just add the extensions of any file type you want to protect from unauthorised download.
That is it.
The major limitation with this approach is the download protection depends on the content of the user’s cookies. Since these can be faked by the technically knowledgeable, the protection is not perfect.
This is not as big a problem as it might first appear, because as long as you give the files and/or the directory non-obvious names, any unauthorised user will not know the required path to the files. They will only know the correct paths if they can log in, and if they can do this, they don’t need to fake any cookies.
While not perfect, this approach should work well for the casual protection of unauthorised downloads, but don’t use it for very sensitive files!