.htaccess Rules for HTTPS and www Redirect

Search engines see http://example.com, https://example.com, http://www.example.com and https://www.example.com as four addresses. These rules send all of them to one version: https://www.example.com. Change the domain to yours.

RewriteEngine On

# 1. Redirect http to https
RewriteCond %{HTTPS} off
RewriteRule ^(.*)$ https://www.example.com/$1 [L,R=301]

# 2. Redirect non-www to www (https)
RewriteCond %{HTTP_HOST} !^www\. [NC]
RewriteRule ^(.*)$ https://www.example.com/$1 [L,R=301]

Check the redirects

curl -I http://example.com/seo-title-tag/
curl -I https://example.com/seo-title-tag/

Both results should show 301 and a Location line with https://www.example.com/seo-title-tag/. If you see a chain of many redirects, simplify the rules.

How it works

  • RewriteCond %{HTTPS} off runs the rule only when the request is not secure.
  • [L,R=301] means last rule and a permanent redirect.
  • !^www\. matches a host name which does not start with www.
  • Both rules send the visitor to the final address directly, so there is no redirect chain.
  • The code works on Apache with mod_rewrite. This server file was not run here, so test it on your own server first, and keep a backup of your old .htaccess.
Note: If your site is behind a proxy or a CDN, the https check may need %{HTTP:X-Forwarded-Proto}, and many hosts offer a setting for the https redirect. See Redirection.

Learn more about the similar topics:
Tutorials
No Content Found.
Exercises & Assignments
No Content Found.
Interview Questions & Answers
No Content Found.