Search code examples
wordpresspdfnginxindexinghotlinking

PDF files protection from external access. Accessible only to authenticated users. WordPress uploads directory


I am running a website and I would like to protect all the PDF files inside the WordPress uploads folder from external access and hotlinking.

I am already using a user authentication to protect the posts attached to these files, but the user authentication doesn't protect the direct link to the PDF file or the indexing of these files from search engines.

I would prefer not to change the default uploads directory since the PDFs are over 1000 with random filenames and attached to various posts with different dates.

The site is hosted on a Debian VPS with Nginx, php5-fpm, and MariaDB.

So far, I have tested the following:

site.conf 1

location /wp-content/uploads/ {
    location ~* \.(pdf)$ {
        valid_referers blocked example.com *.example.com;
        if ($invalid_referer) {
            return 301 https://example.com/services/login-error.html;
        }
    }
}

site.conf 2

location /wp-content/uploads/ {
    location ~* \.(pdf)$ {
        valid_referers blocked example.com *.example.com;
        if ($invalid_referer) {
            deny all;
            return 403;
        }
    }
}

Unfortunately, none of the above configurations work as expected. They block the external access but they also redirect the authenticated user to either 403 or 301 errors.

Any help or suggestion would be appreciated.

Thanks.


Solution

  • So, eventually what I found, after trying all the answers and more, was that while the site.conf #1 was working with the logged-in users for PDF files with URLs starting with https://, it was not working with previous uploads that used to have the http:// in the URL. I had to update the wp_posts table to https://example.com/wp-content/uploads/ and it was finally protecting (only) the PDF files from direct access.

    Of course this is a rough workaround and keep in mind that this method will also protect PDF files that are otherwise publicly available.

    Thanks for all the help.