Force HTTPS instead of HTTP
It is very good when a site works over HTTPS. But sometimes the site is still available over HTTP too, and that spoils the whole picture: visitors from old links and bookmarks get an insecure connection, and search engines see two versions of every page. To avoid this, all pages have to be opened over HTTPS.
Problem: How to force HTTPS on a WordPress site?
Solution: This task is solved with five lines in the .htaccess file:
# Force HTTPS
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteCond %{HTTPS} off
RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]
</IfModule>
Put them at the very top of the file, before the WordPress block, so the redirect happens before anything else. As a result we will have something like this:
# Force HTTPS
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteCond %{HTTPS} off
RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]
</IfModule>
# BEGIN WordPress
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]
</IfModule>
# END WordPress
Do not put your rules between # BEGIN WordPress and # END WordPress: WordPress rewrites this block when the permalinks are saved.
Also check that WordPress Address (URL) and Site Address (URL) in Settings → General start with https://, otherwise WordPress keeps generating HTTP links.
Behind Cloudflare or a load balancer
If HTTPS ends on a proxy (Cloudflare with the “Flexible” mode, a load balancer), Apache always receives HTTP, %{HTTPS} is always off, and the rule above causes an endless redirect. In this case check the header that the proxy sets:
RewriteCond %{HTTP:X-Forwarded-Proto} !https
RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]
NOTE: Browsers remember a 301 redirect for a long time. Test it in a private window first, and only switch to HTTPS when the certificate works on all domains of the site, including www.