301 Redirects to HTTPS (with and without WWW)

I’ve given examples for both “www” and also “without www”. I gave neutral code that works with any site. If you want, you could also replace “%{HTTP_HOST}%” with your domain name. I only have rewrites for Apache HTaccess right now.

Add this code above the #BEGIN WordPress line in your htaccess. 

Method #1

My new favorite method, thanks to Nazar Hotsa who’s researched every method and shared this with me. Awesome community guy with tons of enterprise webhosting experience.

WITHOUT www (all visits go to “https://domain.com”):

# BEGIN Redirects
RewriteEngine On
# 301 redirect www to non-www
RewriteCond %{HTTP_HOST} ^www\.(.*)$ [NC]
RewriteRule ^(.*)$ https://%1/$1 [R=301,L]
# 301 redirect to https
RewriteCond %{HTTPS} off
RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]
# END Redirects

 

WITH www (all visits go to “https://www.domain.com”):

# BEGIN Redirects
RewriteEngine On
# 301 redirect to www
RewriteCond %{HTTP_HOST} !^www\.
RewriteRule ^(.*)$ https://www.%{HTTP_HOST}%{REQUEST_URI} [L,R=301]
# 301 redirect to https
RewriteCond %{HTTPS} off
RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]
# END Redirects

 

Method #2

This one uses less code but has more redirects when you use page tools. It works well but perhaps less performant than the first.

WITHOUT www (all visits go to “https://domain.com”):

RewriteEngine On
RewriteCond %{HTTPS} off
RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]

 

WITH www (all visits go to “https://www.domain.com”):

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

 

Other ways to redirect?

Some people complained my examples used too many redirects. In that case, you’re welcome to research on your own and try other methods of redirection.

Read below and see which one you like best (beware, they all have their implications):

One thought on “301 Redirects to HTTPS (with and without WWW)

Leave a Reply

Your email address will not be published. Required fields are marked *