Enforce https for Drupal

Submitted by kofa on Sun, 02/09/2020 - 16:57

Find this in the Drupal .htaccess file:
# Various rewrite rules.

RewriteEngine on

For simply enforcing https, add these lines:

RewriteCond %{HTTPS} off
RewriteRule ^ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]
RewriteBase /

(the meaning: if a request arrives without https (RewriteCond %{HTTPS} off), send it to the same host with the same path, but with https (RewriteRule ^ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301])

If you want to redirect www.yourdomain.com to yourdomain.com, add this instead:

RewriteCond %{HTTPS} off
RewriteRule ^ https://yourdomain.com%{REQUEST_URI} [L,R=301]

RewriteCond "%{HTTP_HOST}" "^www\." [NC]
RewriteRule ^ https://yourdomain.com%{REQUEST_URI} [L,R=301]
RewriteBase /

(the meaning: if a request arrives without https (RewriteCond %{HTTPS} off; we don't care whether it has the 'www.' prefix or not), send it to the non-prefixed address with same path, but with https (RewriteRule ^ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]; otherwise, if the host name starts with 'www' (non-case-sensitive match), send it to https://yourdomain.com with the same request path (RewriteRule ^ https://yourdomain.com%{REQUEST_URI} [L,R=301]).