How to password protect certain features on a page with .htaccess

Here's an .htaccess trick I often find handy, but have never seen mentioned elsewhere, so I thought I might share. It gives you two routes to accessing the same files: one password protected and the other unprotected. In the files, you can then check how they have been accessed and turn on/off features accordingly.

RewriteEngine On
RewriteRule ^admin$ %{REQUEST_URI}/ [R,L]
RewriteRule ^admin/(.*) $1 [QSA,E=ADMIN:%{REMOTE_USER}]

AuthName "Admin"
AuthUserFile /full_path/.htpasswd
AuthType Basic
Allow From All
<Files admin>
require valid-user
</Files>

If you put this in your root dir (for example), you can now access all files either via /filename or, password protected, via /admin/filename (even though there isn't really an 'admin' directory on the server). In the second case, the server environment variable REDIRECT_ADMIN will store the username used to log in. So now you can do stuff like this in any file:

<?php
$admin = strpos($_SERVER['REQUEST_URI'], 'admin') ? $_SERVER['REDIRECT_ADMIN'] : '';
...
if ($admin) {
   print '<script src="ajaxy_admin_functions.js" type="text/javascript"><script>';
}
?>
<foo>
bar <?=($admin ? "<a href='?delete=765'>delete this<a>" : "")?>
</foo>
<?php
if ($admin && $_GET['delete']) {
   // process request
}
?>

Comments

No comments yet.

Add a comment

Please leave these fields blank (spam trap):

No HTML please.
You can edit this comment until 30 minutes after posting.