Appears to become the area for apache here goes :)

Time tested problem: how and so i redirect HTTP->HTTPS, then and only when HTTPS, do an auth?

Oh - and I would like the majority of it in one snippet that may be Include-erectile dysfunction in multiple <directory> or <location> blocks, so no virtual host level random path based rewrites...

Well, some tips about what I've that does appear to operate:

In the top a VirtualHost block

# Set ssl_off environment variable 
RewriteEngine on
RewriteCond %{HTTPS} =on
RewriteRule ^ - [E=ssl]

Within the location or directory block

RewriteEngine on
# Case 1 redirect port 80 SSL
RewriteCond %{HTTPS} !=on
RewriteCond %{SERVER_PORT} =80
RewriteRule ^ https://%{SERVER_NAME}%{REQUEST_URI} [R=301]

AuthType Basic
AuthBasicProvider external
AuthExternal auth_pam
AuthName "My Underpants"
AuthzUnixgroup on
Order Deny,Allow
Deny from all
Allow from env=!ssl
Satisfy any
Require group nice-users


All that bar the Require's could be abstracted to a snippet file to incorporate in one line on each location

It fixes forcing SSL and authentication together for every location, so less possibility of mistakes


Bloody hell, it's hardly intuitive! May be fragile for those I understand...

It is possible to better way (not too I have found...)?

Comments could be very welcome on whether which has any serious defects :)

Aside Existence could be a lot simpler if Apache were built with a sensible config syntax having a generic

<If expression> </If>

block that may be used anywhere. It's certain special situation blocks for example IfModule, and you have particular situation conditionals like RewriteCond (that is very difficult to grok if you are not accustomed to it).



If you are attempting to pressure the whole site to https, you should use the VirtualHost directives, after which the correct answer is simple:

<VirtualHost *:80>

    RedirectMatch (.*)$1


<VirtualHost *:443>


I have examined your solution also it did not work ...

Following a loooong time searching the answer, searching an excessive amount of and located always exactly the same items that did not work, I finally did this : I personally use SSLRequireSSL as well as an ErrorDocument 403 set up having a static page that contains a JavaScript code (because of this web site page).

in /etc/apache2/conf.d.opt/redirect_if_not_https.conf :

ErrorDocument 403 "<!DOCTYPE HTML PUBLIC \"-//IETF//DTD HTML 2.0//EN\">\
<title>403 Forbidden</title>\
<script language=\"JavaScript\">\
<p>You don't have permission to access that resource using simple HTTP. Please use HTTPS instead.</p>\

(observe that I produced /etc/apache2/conf.d.opt/)

As well as in an application conf, bring that file (for instance in /etc/apache2/conf.d/trac.conf) :

<LocationMatch "/trac">
    # All the classical configurations here
    # ...

    Include conf.d.opt/redirect_if_not_https.conf