Search code examples
.htaccesscodeigniter.htpasswd

Can't password protect specific url in CodeIgniter


I need to protect a specific route/url with password on my codeigniter site.

Base url looks like this:

https://staging.mysite.com/site-name

I want to protect this url with a password using .htaccess

https://staging.mysite.com/site-name/export

Routes looks like this

$route['export']['get'] = 'ExportController/index';
$route['export']['post'] = 'ExportController/export';

I've tried many different answers for similar problems but I just can't get it to work properly, either password is asked everywhere, or it isnt asked at all.

Here is my .htaccess

RewriteEngine on


<IfModule mod_rewrite.c>

   RewriteEngine on
   RewriteCond %{REQUEST_FILENAME} !-f
   RewriteCond %{REQUEST_FILENAME} !-d
   RewriteRule ^(.*)$ index.php/$1 [L,QSA]
</IfModule>

SetEnvIfNoCase Request_URI ^/export SECURED

AuthName "Restricted Area"
AuthType Basic
AuthUserFile "/home/something/path/to/.htpasswd"
AuthGroupFile /
Require valid-user

Satisfy    any
Order      Allow,Deny
Allow from all
Deny from env=SECURED

I think that the problem might be in this part:

SetEnvIfNoCase Request_URI ^/export SECURED

Because I just cant target the url I want, here is some other things I've tried

SetEnvIfNoCase Request_URI ^/site-name/export SECURED
SetEnvIfNoCase Request_URI "^/site-name/export" SECURED
SetEnvIfNoCase Request_URI "^/export" SECURED
SetEnvIfNoCase Request_URI ^(.*)/export SECURED
SetEnvIfNoCase Request_URI .*/export$ SECURED
SetEnvIfNoCase Request_URI .*/export SECURED

Edit:

I've also tried to protect the entire ExportController with like this, password prompt does not appear anywhere.

<Files ExportController>
AuthName "ExportController"
AuthType Basic
AuthUserFile "/home/something/path/to/.htpasswd"
require valid-user
</Files>

Solution

  • I ended up doing this:

    <If "%{THE_REQUEST} =~ m#^GET /site-name/export#">
        AuthType Basic
        AuthName "Password Required"
        AuthUserFile /home/path/to/.htpasswd
        Require valid-user
    </If>
    
    <IfModule mod_rewrite.c>
       RewriteEngine on
       RewriteCond %{REQUEST_FILENAME} !-f
       RewriteCond %{REQUEST_FILENAME} !-d
       RewriteRule ^(.*)$ index.php/$1 [L,QSA]
    </IfModule>