Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Force HTTP AUTH over HTTPS

I have a directory of my website I would like to secure. I am doing this using a .htaccess file to force a HTTP AUTH. I would like to force this HTTP AUTH to be done over HTTPS.

Looking at various solutions on stack overflow here is the point I have got to:

I have the following .htaccess file in the 'top_secret' directory:

SSLRequireSSL
ErrorDocument 403 /rd.php
AuthType Basic
AuthName "Secure Page"
AuthUserFile "/home/usr/.htpasswds/public_html/top_secret/passwd"
Require valid-user

I then have 'rd.php' in my root directory:

<?php
$path = "https://".$_SERVER['SERVER_NAME'].$_SERVER['REQUEST_URI'];
if ( $_SERVER['SERVER_PORT'] == 80) {
    header("Status: 302 Moved\n");
    header("Location: ".$path."\n\n");
}
else {
    header( "Content-type: text/html\n\n");
    echo '?';
}
?>

This works quite well on my desktop computer, however when I browse to the top_secret directory from my iphone in safari (to the HTTPS or HTTP address) I just get a question mark returned. So for some reason the else condition of my php file is being outputted.

I am not exactly sure what this means and how to resolve, any help would be greatly appreciated

like image 915
user2351418 Avatar asked Jul 30 '26 00:07

user2351418


1 Answers

Rather than do this in PHP, I suggest you implement it on the web server layer. Add this to the top of your .htaccess file:

RewriteEngine on
RewriteCond %{HTTPS} off
RewriteRule ^ https://%{HTTP_HOST}%{REQUEST_URI} [R=301,L]

And remove your PHP redirect code.

But this is still going to require log-in before the redirect is issued, with the details being transferred insecurely. What you really need is two <VirtualHost> blocks in Apache. One for port 80 that redirects requests for your directory to HTTPS, and one for port 443 that has the HTTP AUTH configured.

Update

Also it makes no sense to try and issue a 302 redirect within a document that is used as the 403 error document, since the status code has already been set and the document is only being used to generate the body of that response, so it can't now change the response code to 302 because it has already been set to 403. The approach I've outlined above will work, or you could simply deny HTTP requests and serve HTTPS only for that directory.


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!