How to use HTTP authentication for a specific url (not a directory)
I have an htaccess file that uses mod_rewrite to redirect / controller to /index.php?controller=%controller%
Like this:
# Various rewrite rules.
<IfModule mod_rewrite.c>
RewriteEngine on
# Rewrite current-style URLs of the form 'index.php?controller=x&action=y'.
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php?controller=$1 [L,QSA]
</IfModule>
Now what I need to do is make ONE of the controllers work with HTTP authentication. I am not asking if this is the best way to do something, I am just asking how to do it.
Example:
http://www.example.com/ - It requires no auth
http://www.example.com/secret - requires auth
+1
source to share
2 answers
I ended up using PHP for this:
if (in_array($controllerString, $configuration['protected']))
{
$authenticated = false;
if (!isset($_SERVER['PHP_AUTH_USER'])) {
header('WWW-Authenticate: Basic realm="My Realm"');
header('HTTP/1.0 401 Unauthorized');
echo 'You are unatuhorized to access this section of the website.';
} else if ($_SERVER['PHP_AUTH_USER'] == 'admin' && $_SERVER['PHP_AUTH_PW'] == 'admin'){
$authenticated = true;
}
if (!$authenticated)
{
unset($_SERVER['PHP_AUTH_USER']);
die();
}
}
+1
source to share