Search code examples
apachehttpsbasic-authentication

How do I combine basic authentication and https?


I have setup a private website that needs to be accessible by only a few people via the internet. I'd like to setup a combination of basic authentication and https.

So far I have everything works ok if I directly type in https://blah.com/location1. However what I need is to have apache redirect http://blah.com/location1 to https://blah.com/location1 and THEN do basic authentication i.e I don't want basic authentication to be done before the redirection. At the moment this is what I have on my apache config.

WSGIScriptAlias /site /path/to/site/apache/site.wsgi

<Directory /path/to/site/apache>
    WSGIApplicationGroup %{GLOBAL}
    Order deny,allow
    Allow from all
</Directory>

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

    AuthType Basic
    AuthName "Site login"
    AuthUserFile /path/to/site/.htpasswd
    Require valid-user
</Location>

Note: I only need the authentication for /site. So I should be able to access http://blah.com/site1, http://blah.com/site2 without needing authentication.


Solution

  • The problem with the rewrite rules that "convert" HTTP requests into HTTPS requests is that they don't prevent the first request to be made over plain HTTP (as you get a redirect to the HTTPS URL).

    What you could do is split your site into two virtual hosts: one for HTTP and one for HTTPS.

    On the HTTP virtual host, implement the rewrite if you want, but forbid access to <Location /location1> in all cases (only do the rewrite).

    On the HTTPS virtual host, configure <Location /location1> with basic authentication.