The proper way to redirect a root domain (non-www) to the equivalent on the www.
subdomain URL is with a single page-level 301 redirect. Page level means that if someone visits https://domain.com/about/
we want them to be redirected to https://www.domain.com/about/
.
Like wise, if we want all www URL’s to the root domain, then when someone visited https://www.domain.com/about/
we’d want them to be redirected to https://domain.com/about/
. Many of the other tutorials I see documented around the web do not do this, which is bad for UX and SEO.
The best way to handle this in CloudFlare is with page rules that set a forwarding URL. Wildcard variables make it possible to handle a page to page redirect with a single rule. Wildcards are added to the URL field as a *
character, and each one corresponds to a variable we can reference in the forwarding address. Variables are used in the destination URL with a $
followed by a number starting at 1
, so to refer to the first wildcard we use $1
, $2
for the second wildcard, and so on. In most cases, only one is used, but it’s good to know how it works for more advanced scenarios.
Here is an example page rule that will redirect all URL’s from a root domain (domain.com
) to the corresponding URL on the www
subdomain (www.domain.com
).
domain.com/*
To use this replace domain.com
with your own domain, then click Save Page Rule. That’s it, you’ll redirect all URL’s to the root domain of your website automatically with a single 301 redirect rule.
Here is an example page rule that will redirect all URL’s from a www
subdomain to the corresponding URL on the root domain (domain.com
).
www.domain.com/*
To use this, replace domain.com
with your own domain, then click Save Page Rule. That’s it, you’ll redirect all URL’s to the root domain of your website automatically with a single 301 redirect rule.
Why should we do this at all? Well, you don’t have to. You could have your site load the same content at two URL’s, and if you properly set a canonical tag it’s not an SEO issue.
But it’s almost always a bad idea that adds unnecessary complexity:
Overall there’s just no compelling reason to not redirect and keep things consistent. There may be extreme edge cases out there, but in 99% of the scenarios I’ve seen it’s best to use a 301 to or from your root domain and www.
.