Before we show how redirect non-WWW URL to WWW using Cloudflare, let's see why it is important that a website cannot be accessed both via WWW and without WWW (non-WWW).
There are many website owners who insist on web developers using web addresses like:www.example.com". Saying that this defines a site. Indeed, this was many years ago, when many did not really understand the true meaning of WWW.
In the technical terms of configuring a web address, the prefix "www"it's just a subfield as it is"abcd.example.com". It has nothing special and only helps with a web address with a larger number of characters. Moreover, Google recommends in good SEO practices that websites do not contain WWW.
A real problem is when a web page is accessible both on a URL with WWW and on one without WWW. In SEO practices, it is called "duplicate content" and is penalized. That is why it is indicated if a website does not use WWW, when accessing https://www.example.com users to be redirected to https:/example.comwith 301 redirect code. Code that means "permanent redirection".
It is also possible that on www.example.com we have a website, and on example.com we have a completely different website. Hosted on different servers or on the same server.
If you already have a website with WWW in the URL, then it is recommended to leave it as it is, but to redirect 301 all requests coming from non-WWW to WWW. If a visitor accesses the web page "example.com/demo.html” to be automatically redirected to “www.example.com/demo.html".
How to redirect non-WWW URL to WWW using Cloudflare
1. Log in to your Cloudfare account and go to the domain for which you want to redirect non-WWW to WWW. The domain must have Cloudflare enabled. So is DNS. Go to settings first DNS > Records and check that this service is active for A example.com si CNAME or A for www. Proxy status to be active.
2. Go to the domain settings in Pages → Page Rules. In the free version of Cloudflare you can set 3 rules for each domain. Create Page Rule.
3. Enter in the first field URL without WWW, followed by
$1. https://example.com/$1. This means that the permalink redirection of all web pages is preserved. meaning https://example.com/abcd.html will be redirected to https://www.example.com/abcd.html. The user will reach the content of the page.
In the settings for the rules, you will choose "Forwarding URL” and the redirection code will be chosen permanently 301.
The destination URL will be: https://www.example.com.
Save and Deploy Page Rule.
The new rule will take effect almost immediately.
This is the simplest method of redirecting web pages and does not involve access or knowledge of .htaccess or NGINX directives.