The perfect HTTPS and www redirect setup in Cloudflare

My main domain name is https://www.website.com, and I’ve been trying to work out the optimal settings in Cloudflare to make all other variants redirect to this single domain.

I’m looking to achieve this:

http://website.com     -> https://www.website.com
http://www.website.com -> https://www.website.com
https://website.com    -> https://www.website.com

I’ve outlined the settings I’ve made below.

1. HTTPS redirect.

The first thing I’ve done is redirect all http to https by enabling SSL/TLS > Edge Cerificates > Always Use HTTPS. So now the following redirects are working:

http://website.com     -> https://website.com
http://www.website.com -> https://www.website.com
https://website.com    -> https://website.com

I also enabled HSTS for good measure. Is this preferable?

So that takes care of the HTTPS redirects. Now I just need to sort out the non-www to www redirects.

2. Non-www to www redirect.

Next I set up the following two Page Rules:

1. Forwarding URL (301): https://website.com/* -> https://www.website.com/$1
2. Forwarding URL (301): http://website.com/* -> https://www.website.com/$1

So now all the redirects seem to work perfectly, and everything points to my primary domain:

http://website.com     -> https://www.website.com
http://www.website.com -> https://www.website.com
https://website.com    -> https://www.website.com

I think the second page rule is a little redundant, but it avoids having a redirect chain like http://website.com -> https://website.com -> https://www.website.com. (NOTE: See Edit Below)

Also, the * and $1 in the page rules mean that all requests are forwarded as they are, instead redirecting all requests to the root domain only.

Anyway, is there a better way to achieve this in Cloudflare? Or are these settings okay?

Thanks in advance.

EDIT:

I don’t think that second page rule redirect is a good idea. According to https://hstspreload.org I should just redirect to https://website.com directly first without the www prefix. This is so the domain can be included in a browser’s preload list, as long as I use these settings for HSTS:

  • Max Age Header = 12 months
  • Include Sub Domains = On
  • Preload = On

Pay attention with HSTS, especially if you do the preload list. You won’t be able to get off easily, you need to be able to manages HTTPS only on all subdomains for basically forever.


With regards to the redirect, you should only have a rule without the scheme (so from example.com/* to www.example.com/$1), it will be merged to one single redirect.

It works regardless of the actual domain you are redirecting to (on mines I do example.com to www.example.com and they preloaded fine).

2 Likes