Have you ever needed to make sure your website works with both www and non-www versions?
I did too!
My website is served at https://thesshguy.com, but I also wanted https://www.thesshguy.com to work.
The Problem with Two Versions
The first thing I tried was to add A
and AAAA
DNS records for both versions. While that does work, there's a problem with this approach. Google and other search engines get confused because it looks like there are two versions of my website.
When Google tries to index my website, there's no clear answer to which is the canonical version.
So what can we do instead?
Improve Things with Redirects
Since we have two versions, we can redirect one to the other to improve things. This tells web crawlers which version is the main one. I used a Cloudflare rule to redirect the www version to the non-www version.
Note: I had to include DNS records and add a redirect rule for things to work correctly.
Here's how you can do it too.
Steps to Set Up the Redirect
Note: Make sure to use your own website in place of mine.
Log into your Cloudflare account
Go to Rules > Redirect Rules
Click Create rule under Single Redirects
Name your rule (I named mine "WWW to Non WWW")
Set up a custom filter like this:
Field:
Hostname
Operator:
equals
Value:
www.thesshguy.com
URL redirect Type:
dynamic
Expression:
concat("https://thesshguy.com", http.request.uri.path)
Status Code:
301
(permanent redirect)
Here's what my rule looks like:
And that's it!
Now your www version will redirect to the non-www version. Hopefully, this helps you set up your own Cloudflare redirects!