Superman Superman - 1 year ago 108
Linux Question

Prevent direct access to PDF files - Nginx

Lately I changed a server for my website. Before I used Apache server. Now my website works on Nginx server. That is why I can't use

any longer.

I would like to prevent users from opening some pdf files by typing the link to the files in the browser. I want them to be able to open the files by clicking on the links to the files from my website. So far I used the code below; it works well when it comes to preventing hotlinking images, but it doesn't prevent direct access to pdf files.

location ~ /folder/with/pdffiles/(.+\.(?:jpg|pdf|jpeg|gif|png|bmp|ic$

valid_referers none blocked server_names * mydomain.* ~\.mydomain\.;
if ($invalid_referer) {
return 444;
try_files $uri @ghost;

Answer Source

While you could do something like:

if ($http_referer = "") { return 403; }

Inside of your nginx location, if conditions are not a recommended thing to do (see If is Evil).

The standard practise today is to place restricted files outside the web-server root folder (doesn't matter what it is - Apache or nginx), and serve the files via a server-side script that can do anything you want – not only check the referrer, but perhaps a user session or authentication.