3
votes

I am trying to protect my website with a directory protection code. The website is in PHP.

My website has https and it is like https://www.example.com.

When I Open the website it is asking for username and password twice. I think it is taking once for http and once for https.

Can anyone please help me how to solve this problem.

Below is my .htaccess file code

options -multiviews
<IfModule mod_rewrite.c>
RewriteEngine On 
RewriteBase /
RewriteCond %{HTTP_HOST} ^example.com$ [NC,OR]
RewriteCond %{HTTP_HOST} ^www.example.com$ [NC]
RewriteRule ^(.*)$ https://www.example.com/$1 [R=301,L]
</IfModule>

AuthType Basic
AuthName "example.com"
AuthUserFile /www.example.com/web/content/.htpasswd
Require valid-user

<IfModule mod_security.c> 
   # Turn off mod_security filtering. 
   SecFilterEngine Off 
   # The below probably isn't needed, 
   # but better safe than sorry. 
   SecFilterScanPOST Off 
</IfModule>

Thanks in advance for any help.

1

1 Answers

4
votes

You're getting authentication dialogue twice because Apache runs mod_auth directive before mod_rewrite directive. Also authentication session set in HTTP URL isn't valid in HTTPS URL anymore therefore it Apache has to follow the BASIC auth directive under HTTPS as well.

There can be some work-around type solutions to skip BASIC auth for http URL and do it only for HTTPS but it is not straight forward.

UPDATE: Here is a workaround solution that you can use to avoid showing BASIC auth dialogue twice.

RewriteEngine On 
RewriteBase /

# redirect to HTTPS and set a cookie NO_AUTH=1
RewriteCond %{HTTPS} off
RewriteRule ^ https://%{HTTP_HOST}%{REQUEST_URI} [R=301,L,CO=NO_AUTH:1:%{HTTP_HOST}]

# If cookie name NO_AUTH is set then set env variable SHOW_AUTH
SetEnvIfNoCase COOKIE NO_AUTH=1 SHOW_AUTH

# show Basic auth dialogue only when SHOW_AUTH is set
AuthType Basic
AuthName "example.com"
AuthUserFile /www.example.com/web/content/.htpasswd
Require valid-user
Order allow,deny
allow from all
deny from env=SHOW_AUTH
Satisfy any

Since cookie is only set for http://domain.com therefore env variable is also set only once and BASIC auth dialog is also shown only once.