Superman
Superman

Reputation: 23

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 .htaccess 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.com mydomain.* ~\.mydomain\.;
       if ($invalid_referer) {
         return 444;
        }
        try_files $uri @ghost;
}

Upvotes: 1

Views: 2544

Answers (1)

Denis Mysenko
Denis Mysenko

Reputation: 6534

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.

Upvotes: 1

Related Questions