ssl

Redirect to https with Apache

Snippet

Redirect to https in .htaccess

See also, redirect before authenticating.

# Various rewrite rules.
<IfModule mod_rewrite.c>
  RewriteEngine on
 
  # if not already HTTPS
  RewriteCond %{HTTPS} !=on
  RewriteRule ^/?(.*) https://%{SERVER_NAME}/$1 [R,L]
 
  # Set "protossl" to "s" if we were accessed via https://.  This is used later
  # if you enable "www." stripping or enforcement, in order to ensure that
  # you don't bounce between http and https.
  RewriteRule ^ - [E=protossl]
  RewriteCond %{HTTPS} on
  RewriteRule ^ - [E=protossl:s]
 
  # To redirect all users to access the site WITHOUT the 'www.' prefix,
  # (http://www.example.com/... will be redirected to http://example.com/...)
  RewriteCond %{HTTP_HOST} ^www\.(.+)$ [NC]
  RewriteRule ^ http%{ENV:protossl}://%1%{REQUEST_URI} [L,R=301]
</IfModule>

Redirect to https before basic Auth

Snippet

Some directories need to redirect to https before you check auth, otherwise people are typing in their passwords in clear text before they are redirected. Which would SUUUUuuuUUUuck.

So, for Apache > 2.4, use configuration sections, and redirect before authenticating.

# Redirect to HTTPS
RewriteEngine On
RewriteCond %{HTTPS} off
RewriteRule (.*) https://%{HTTP_HOST}%{REQUEST_URI} [R,L]
 
# Authenticate users only when using HTTPS
<If "%{HTTPS} == 'on'">
    AuthType Basic
    AuthName "Yep, you need to provide a password."
    AuthUserFile /etc/path/to/htpasswd.file
    # this is so the next 'Require' directive doesn't override any merged previously
    AuthMerging And
    Require valid-user
</If>