How to redirect from non WWW to WWW domain in Cloudflare Redirect Rules

Now, that the Cloudflare Page rules are deprecated, I bring to you a short guide explaining how to migrate your WWW redirect rule to the new Redirect Rules.

To get started, go to Cloudflare Dashboard, Select your Domain, and Go to the Rules > Redirect Rules section on the sidebar.

Alternatively, you can click on the link below 👇.
Cloudflare Dashboard Redirect Rules.

Setting up the Rule

Once you are there, Create a new Single Redirect Rule and name it something simple like I have in the screenshot below.

Then, on the fields, select Hostname; Operator equals and then enter your domain name on the value. I have used my own domain, aih.app as example in the screenshot below.

Once that’s done, scroll down to the “Then…” section and select Dynamic type from the dropdown.

Copy and paste the following expression and check the Preserve query string option.

concat("https://www.", http.host, http.request.uri.path)

It should look like the following screenshot.

The above expression combines the https://www part with your hostname i.e. your domain with the URI path. You can learn more about Cloudflare’s concat expression here.

Note: I used first as Place at order because I had no other rules. But if you have other rules then, you should consider their order first before selecting this option.

Finally, you can click on Deploy and it should start redirecting your requests.

Testing

This stage is optional, but you can test if the redirects are working by going to the non WWW url and seeing if it redirects to the www URL.

or you can use the cURL in your terminal using the following command below.

curl -I yourdomain | grep location

We can see that it is redirecting to the WWW version.

We can also see if it is properly redirecting URI paths by adding any random path.

We can see that it redirected to the correct path.

It also redirects the HTTP urls. If you do not want it to redirect to https you can type in http://www in the expression above.

If you have any suggestions or comments please feel free to comment below 👇.