Properly force SSL with .htaccess, no double authentication
If you have server-side execution such as php or cgi, then set your ErrorDocument to a file that does not require authentication. This file should redirect the client to the proper location. Apache will set several REDIRECT_ - prefixed environment variables to help you out, and the original environment is preserved -- see http://httpd.apache.org/docs/trunk/custom-error.html.
In your .htaccess
, do as your second example above, but make the ErrorDocument an internal document:
SSLOptions +StrictRequire
SSLRequireSSL
SSLRequire %{HTTP_HOST} eq "example.com"
ErrorDocument 403 /err_redirect.php
AuthName "Locked"
AuthUserFile "/home/.htpasswd"
AuthType Basic
require valid-user
<Files /err_redirect.php>
AuthType none
</Files>
Then, in that error document, send the appropriate HTTP status and Location header. Here's a simple example in php:
<?php
header("Location: https://" . $_SERVER["HTTP_HOST"] . $_SERVER["REQUEST_URI"]);
?>
This works perfect for what I'm trying to do, I have some PHP based admintools in respective directories under /admin/
, in /admin/.htaccess
I have listed:
SSLOptions +StrictRequire
SSLRequireSSL
SSLRequire %{HTTP_HOST} eq "www.example.com"
ErrorDocument 403 https://www.example.com/admin/
AuthName "Enter your credentials"
AuthType Basic
AuthUserFile /etc/httpd/passwd/passwordfile
Require user valid-user
when going to non-secure example.com/admin
it redirects it to secure example.com/admin
, then prompts for authentication.