Jaapze
Jaapze

Reputation: 742

codeigniter: protect controller with htaccess

I would like to protect 1 controller from my Codeigniter project with the following htaccess code placed in the root:

RewriteEngine on
RewriteCond %{HTTP_HOST} !^www\.
RewriteRule ^(.*)$ http://www.%{HTTP_HOST}/$1 [R=301,L] 
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule .* index.php/$0 [PT,L]

<Files admin>
AuthName "admin"
AuthType Basic
AuthUserFile /home/domain/domains/domain.nl/.htpasswd/public_html/.htpasswd
require valid-user
</Files>

When i go to domain.nl/admin i do get a prompt asking for the credentials. But when i click cancel it still proceeds to the admin page. How can i fix this?

Upvotes: 2

Views: 3530

Answers (1)

Dino Babu
Dino Babu

Reputation: 5809

Another simple way. Put this in top of your Admin Controller.

  public function __construct() {
    parent::__construct();
    if (!isset($_SERVER['PHP_AUTH_USER']) || $_SERVER['PHP_AUTH_USER'] != 'username' || $_SERVER['PHP_AUTH_PW'] != 'password') {
      header('WWW-Authenticate: Basic realm="MyProject"');
      header('HTTP/1.0 401 Unauthorized');
      die('Access Denied');
    }
  }

Upvotes: 9

Related Questions