How to force HTTPS in a directory AND force HTTPS authentication

I am wondering what is the best way to force HTTPS authentication.

When I have this in my .htaccess file:

AuthType Basic
AuthName "Developer"
AuthUserFile /usr/local/etc/apache22/passwords/passwords
Require user david

Authentication works, but it authenticates on port 80 by sending a password in a box.

So, I decided to add a Redirect rule to redirect all non-HTTPS requests to equivalent HTTPS requests:

RewriteEngine On
RewriteCond %{SERVER_PORT} 80
RewriteBase /~david/
RewriteRule ^(.*)$ https://myserver.tld/~david/$1 [R,L]

This also works, but first it authenticates on port 80, then forwards, and then authenticates again on port 443. I DO NOT want to authenticate on port 80 because the password will be sent in clear text. I could not find a good way to redirect HTTPS immediately and then confirm.

The only way I could figure out how to do this is to do the following:

AuthType Basic
AuthName "Developer"
AuthUserFile /usr/local/etc/apache22/passwords/passwords
Require user david
ErrorDocument 403 /403.php
SSLRequireSSL

403.php PHP script / :

<?php

header('Location: https://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI']);

?>

. SSL, , 80, HTTPS.

. ?

+5
1

, , , , HTTPS, HTTP . ( - " ", ).

/ - , :

<VirtualHost *:80>
   ...
   RewriteRule ^/foo/bar/?(.*)$ https://myserver.tld/foo/bar/$1 [R,L]
   # and to guard against typo's...
   <Directory /foo/bar/>
       deny from all
   </Directory>
</VirtualHost>


<VirtualHost *:443>
   ...
   <Directory /foo/bar/>
       BasicAuth .. etc.
       allow from all
   </Directory>
</VirtualHost>

.

Dw.

+13

All Articles