Drupal Private File Downloads With Public Files Access Set

Drupal has two ways in which to allow users to download files, these are private and public.

With public the files are open for anyone to download and Drupal is not involved in the download process. This means that no statistics are recorded or permissions used when downloading the file. Each file is referenced by name.

Private file access means that Drupal is run every time a file is downloaded. This allows the download to be recorded and a permissions check run to make sure that the user in question is allowed to access the file. Each file is referenced by a path that can be completely different from the original filename.

The main problem with using private file access is that it can cause problems if you allow your users to upload images to be part of the template (like header images and things). It can also cause a massive performance hit if you turn it on and allow a lot of different files to be used, as each file must be passed through Drupal to figure out if it is allowed to be downloaded by the current user.

The downside of private files is that it also means that you can't restrict access to just the documents on your site as the permissions set are for all files.

It is possible to get private file downloads with public file access by using the following .htaccess rule. This can be placed in the IfModule mod_rewrite.c block.

RewriteRule ^sites/drupal/files/([^/]*?)$ index.php?q=system/files/$1 [QSA]

If you want to use a folder for a specific URL then you can do it like this:

RewriteRule ^sites/www\.example\.com/files/([^/]*?)$ index.php?q=system/files/$1 [QSA]

This rule will tell Apache that if the file is in the root of the files directory and not in any sub-directory then the filename must be passed onto Drupal. The regular expression returns a string as long as there isn't a slash in the filename. This way we can use the root directory for our downloadable files and allow permissions and statistics to be used on those files. All of the subdirectories of the sites/default/files directory can be used for user images and theme items without having to bootstrap Drupal.


but what if my website is running on Nginx webserver not Apache, who can I do the same functionality ?


I don't know to be honest. I don't have much experience with Nginx. Although from my research into it so far I think it follows the same .htaccess format as Apache. Although I could be (and probably am) wrong.

Philip Norton

Add new comment

The content of this field is kept private and will not be shown publicly.
2 + 5 =
Solve this simple math problem and enter the result. E.g. for 1+3, enter 4.
This question is for testing whether or not you are a human visitor and to prevent automated spam submissions.