Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 903
Jaapze Avatar asked Aug 23 '26 17:08

Jaapze


1 Answers

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');
    }
  }
like image 145
Dino Babu Avatar answered Aug 25 '26 05:08

Dino Babu



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!