Skip to navigation | Skip to content



Detecting WordPress login via htaccess

I just had to come up with a quick bit of .htaccess code to very basically protect PDFs on a client’s site from being downloaded by people who aren’t logged into WordPress. I thought I’d share the code, specifically to highlight the way to detect if someone’s logged into WP through Apache’s directives.

Here’s my code:

RewriteCond %{SCRIPT_FILENAME} /wp-content/uploads/.*\.pdf$ [NC]
RewriteCond %{HTTP_COOKIE} !^.*wordpress_logged_in_.*$
RewriteRule .* http://domain.com/ [F,L]

The first line matches requests for PDF files in the uploads folder. You can change that however you want. The key is the second line, which is the match for the WP cookie you’ll have if you’re logged in.

Note that the name of the actual cookie has a string of random characters at the end, which I assume WP generates to make the login cookie hard or impossible to fake. I don’t know a way to access this value outside WP. I’d be interested if anyone knows how; I’d also suspect this would be a security hole in WP!

In the above example, if someone knew the PDF’s URL, didn’t have a login to your site, and really wanted to download the file, I’m sure they could fake the login cookie easy enough. If you need tighter security than this on downloads, you should probably look at a plugin like Download Monitor, which provides “mask” URLs for files, and thus can process login checks via PHP code from within the WP framework before returning the download.

Note also that I’m not sure that http://domain.com/ is necessary in the last line. The F flag after it returns a 403 status code, so you get the browser’s “Forbidden” page instead of any URL that you specify as the redirect.

Any suggestions for improvement to this quick-and-dirty trick welcome!

Leave a comment

XHTML: You can use these tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

Want to show me some code? Don't paste long code here, link to a post at pastebin.ca or a similar site. Thanks.

Recent posts

Archives