How to Protect Uploads, if User is not Logged In?

I use WordPress for a private site where users upload files.
I use the “Private WordPress” to prevent access in to the site if the user is not logged in.

I would like to do the same to the files uploaded in the uploads folder.

So if a user its not logged in they wont be able to access to :
https://xxxxxxx.com/wp-content/uploads/2011/12/xxxxxxx.pdf
if they try to access but they are not logged then they should be redirected to login page for example.

I found a plugin called private files but last time updated was in 2009 and it does not seems to work on my WordPress.

Anyone know any method?
Hotlinking method will be enough to protect this?

I also found this method :

# BEGIN WordPress
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteCond %{REQUEST_URI} ^.*uploads/private/.*
RewriteCond %{HTTP_COOKIE} !^.*wordpress_logged_in.*$ [NC]
RewriteRule . /index.php [R,L]
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]
</IfModule>
# END WordPress

But then any user that replicate the cookie could pass this right?
Regards

Only checking if the cookie exists, is not much of a strict protection.

To get a stronger protection, you can pass or “proxy” all requests to the uploaded folder (exemplary uploads in the following example) through a php script:

RewriteCond %{REQUEST_FILENAME} -s
RewriteRule ^wp-content/uploads/(.*)$ dl-file.php?file=$1 [QSA,L]

All requests to uploaded files (which includes images in posts) would go to dl-file.php which then can do verify if the user is logged in or not.

If the user is not logged in, your sites login-form will be shown. After the user logged in, she will get redirected back to the file and can download it now.

Exemplary dl-file.php.

Something similar can be found in \wp-includes\ms-files.php in your wordpress installation, but that one is for multisite and w/o the login check and redirects.

Depending on how much traffic you have, it could be wise to better integrate this with your server, e.g. X-Accel-Redirect or X-Sendfile headers.

Leave a Comment