Posted By

depiction on 11/14/12


Versions (?)

Who likes this?

1 person have marked this snippet as a favorite


WordPress: Restrict Uploads folder access to logged in users

 / Published in: PHP


You might have some sections of your WordPress site that are only accessible for your WordPress user. Pretty easy to protect the page or post in WordPress for only the registered user but what about the attachments of the post/page (files, images)?

They won’t be protected by default, this means if a request is made directly to the file it can be accessed without any password. There is potentially the solution where you protect the files in a directory with htaccess password, but do you really want to manage new set of username and password outside or WordPress? Not really.

Here is the solution, use htaccess to check if a user is logged in the WordPress site when accessing the files area, if not then redirect to the WordPress login page. Here is the new .htaccess:

(These are the 3 new lines:) RewriteCond %{REQUESTURI} ^.uploads/. RewriteCond %{HTTPCOOKIE} !^.wordpressloggedin.$ [NC] RewriteRule . /wp-login.php?redirectto=%{REQUESTURI} [R,L]

To prevent WordPress from overwriting this later, CHMOD the .htaccess file to 444.

  1. # BEGIN WordPress
  2. <IfModule mod_rewrite.c>
  3. RewriteEngine On
  4. RewriteBase /
  5. RewriteCond %{REQUEST_URI} ^.*uploads/.*
  6. RewriteCond %{HTTP_COOKIE} !^.*wordpress_logged_in.*$ [NC]
  7. RewriteRule . /wp-login.php?redirect_to=%{REQUEST_URI} [R,L]
  8. RewriteRule ^index\.php$ – [L]
  9. RewriteCond %{REQUEST_FILENAME} !-f
  10. RewriteCond %{REQUEST_FILENAME} !-d
  11. RewriteRule . /index.php [L]
  12. </IfModule>
  13. # END WordPress

Report this snippet  

You need to login to post a comment.