Mark S.
Mark S.

Reputation: 1082

How do I 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 be able to do is make ONE of the controllers work with HTTP Authentication. I'm not asking if this is the best way to do things, I'm simply asking how to do it.

Example:

http://www.example.com/ - It requires no auth
http://www.example.com/secret - requires auth

Upvotes: 1

Views: 2866

Answers (2)

ken
ken

Reputation: 5086

<Location /secret>
  AuthName localhost
  AuthType Basic
  AuthUserFile <file>
  Require valid-user
</Location>

Upvotes: 4

Mark S.
Mark S.

Reputation: 1082

I ended up using PHP to do it:

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();
    }
} 

Upvotes: 1

Related Questions