Saturday, April 13, 2013

htaccess Rewrite before Authentication - HTTP to HTTPS

Error

When having an "htaccess" file which contains "Rewrite" then "Authentication" the Authentication is done before the rewrite 

This happenes when you need to make sure the user is authenticating on HTTPS instead of HTTP so you need to do the rewrite before the HTTP Basic Authentication


RewriteEngine On
RewriteCond %{HTTPS} off
RewriteRule (.*) https://%{HTTP_HOST}%{REQUEST_URI}



AuthType Basic
AuthName "protected area"
AuthUserFile /FILE_PATH
Require user USER


Solution

There are 2 solutions for Apache 2.2 installations


Solution #1 - Easiest

Just enclose the authentication by a <FilesMatch "."> block

RewriteEngine On
RewriteCond %{HTTPS} off
RewriteRule (.*) https://%{HTTP_HOST}%{REQUEST_URI}


<FilesMatch ".">

AuthType Basic
AuthName "protected area"
AuthUserFile /FILE_PATH
Require user USER

</FilesMatch>


Solution #2

Require SSL and point the error document to a file which redirects to HTTPS

RewriteEngine On
RewriteCond %{HTTPS} off
RewriteRule (.*) https://%{HTTP_HOST}%{REQUEST_URI}

SSLRequireSSL
ErrorDocument 403 /PATH_TO_A_PAGE_TO_REDIRECT_TO_HTTPS


AuthType Basic
AuthName "protected area"
AuthUserFile /FILE_PATH
Require user USER


No comments:

Post a Comment