For testing purposes, I have a password-protected clone of my website, accessible using a subdomain such as dev.example.com
. I am using basic authentication
, and all traffic should be transferred using https
. Hence, any requests using http
must be redirected to https
before authentication. I have tried the following .htaccess
file.
RewriteEngine On
# Rewrite any requests to ip addresses or *.example.com to dev.example.com
RewriteCond %{HTTP_HOST} !^dev\.example\.com$ [NC]
RewriteCond %{THE_REQUEST} \s(\S*)\s
RewriteRule ^ https://dev.example.com%1 [L,NE,R=302]
# Rewrite to https
RewriteCond %{HTTPS} off
RewriteCond %{HTTP:X-Forwarded-Proto} !https
RewriteRule ^ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=302]
# Require authentication
AuthName "Restricted development environment"
AuthType Basic
AuthUserFile /var/www/html/.htpasswd
Require valid-user
I'm checking both %{HTTPS}
and %{HTTP:X-Forwarded-Proto}
to support both the case when the client is connecting the server directly, and also the case when the server is behind a load balancer, and the traffic between the load balancer and the server is using http
.
The idea is that the [L]
flag should cause the redirects to happen before authentication, but this does not seem to be the case. When accessing http://dev.example.com
, authentication pops up. If I enter the credentials correctly, I'm redirected to https://dev.example.com
, and authentication pops up again.
I found this similar question, where the [L]
flag is not used. The suggested solution there is to set an environment variable when https
is in use, and only allow access when that variable is set. But I don't understand why I can't just use the [L]
flag instead. Maybe I've misunderstood it's use and meaning. Why isn't the redirect done before authentication when using the [L]
flag?