17
2017
Only allow access to specific wordpress upload types if logged in
I had an interesting problem earlier today where I’d created a custom WordPress plugin which was to be logged-in-user only, and happened to include some uploaded content.
So in proper developer format, I made sure to leverage WordPress’ great media uploading capabilities as opposed to arbitrarily creating something to store files within the plugin directory, but soon discovered a problem!
Though you could only browse the actual list of files if you were logged in, Google had successfully indexed the uploads directory. Now, fortunately they weren’t sensitive information, however, they also were not public domain.
Tasks:
- Prevent search engines from indexing them moving forward
- Prevent access to non-logged in users beginning immediately
After doing some research, I located many plugins to handle media uploads and protect them through sitemap.xml files, individual htaccess directives, different interfaces, etc…, however, zero of those addressed the two issues.
The Solution
#Just in case- prevent directory listing
Options All -Indexes
# Discourage search engines from indexing these file types
<IfModule mod_headers.c>
<FilesMatch "\.(pdf|doc|docx|ppt|pptx)$">
Header append X-Robots-Tag "noindex"
</FilesMatch>
</IfModule>
# And explicitly redirect to your site homepage if someone
# not logged in to your wordpress site tries to view them
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteCond %{HTTP_COOKIE} !^.*wordpress_logged_in.*$ [NC]
RewriteRule .*.(pdf|doc|docx|ppt|pptx)$ http://yoursitehomepage.com/ [NC]
</IfModule>
Just change “http://yoursitehomepage.com/” to your desired redirect location, and put the above contents in:
/wp-content/uploads/.htaccess
Leave a comment
Recent Snippets
- htaccess : Only allow access to specific wordpress upload types if logged in
- MySQL : Query WordPress Database for Invalid Media Filenames
- PHP : Get Actual IP Address with PHP
- JavaScript : Allow Tab in Textarea
- PHP : Clean sanitized database contents on output
- htaccess : Force www. prefix in URIs
- PHP : Force File Download with Correct Content Type
- Wordpress : Disable upgrade notification