Monday, January 27, 2014

Password Protect WordPress Attachments (files)

I had a website where users can upload important file to share. i used one of the option provided by web host in the cp called, 'Secured folder'. so other people on the net cannot access the file.

Well, recently the option no longer supported, and i had to look around on the net to find a simpler solution other than subscribing to an 'additional services'. 

so i found one, which is this.

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:
# BEGIN WordPress
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteCond %{REQUEST_URI} ^.*uploads/.*
RewriteCond %{HTTP_COOKIE} !^.*wordpress_logged_in.*$ [NC]
RewriteRule . /wp-login.php?redirect_to=%{REQUEST_URI} [R,L]

RewriteRule ^index\.php$ – [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]
# END WordPress
We simply have protected the whole uploads area and redirect to login if the user is not logged. You can protect a different directory.

basically just create a file called .htaccess (note that.htaccess is the extension, if you create .htaccess.php for examples, it wont work) with the code above and place it inside the folder that you want to protect.


No comments:

Post a Comment