Force HTTP AUTH over HTTPS
I have a directory of my website that I would like to protect. I am doing this using a .htaccess file to force HTTP AUTH. I would like to force this HTTP-ATH to do over HTTPS.
Looking at various stack overflow solutions here is the point I got:
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
Then I 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 well on my desktop, however, when I browse the top_secret directory from my iphone on safari (to HTTPS or HTTP address), I just return the question mark. So for some reason the else clause of my php file is being output.
I'm not really sure what this means and how to resolve, any help would be greatly appreciated
source to share
Instead of doing it in PHP, I suggest you implement it at the web server level. Add this to the top of your file .htaccess
:
RewriteEngine on
RewriteCond %{HTTPS} off
RewriteRule ^ https://%{HTTP_HOST}%{REQUEST_URI} [R=301,L]
And remove the PHP redirect code.
But this will still require logging in before the redirect is issued, and the data will be transmitted insecurely. You really need two blocks <VirtualHost>
in Apache. One for port 80, which redirects requests for your directory to HTTPS, and one for port 443 with the HTTP AUTH setting.
Update
It also makes no sense to try to pass a 302 redirect in a document that is being used as a document with a 403 error, since the status code is already set and the document is only used to generate the body of this response, so now it cannot change the response code to 302 since it is already set to 403. The approach above will work, or you can simply deny the HTTP requests and serve HTTPS for that directory only.
source to share