I was looking for a quick way to redirect all of the URLs of my site from the www to the non-www version.

Meaning, when trying to enter https://www.example.com it will automatically be changed to https://example.com, so that there is only one active URL structure.

The redirection should also preserve the path, so when trying to access https://www.example.com/post-name/ for instance, the URL will be changed to https://example.com/post-name/.

I then found this great solution in “Cloudflare Community”, which explains how this can be done via Cloudflare.

Check DNS

  1. Log in to your Cloudflare account.
  2. On the Cloudflare homepage, click on the desired site.
  3. Click the “DNS” tab in the left menu.
  4. Under the “DNS management” section, make sure that both www and non-www (root/@) names are listed and marked as “Proxied” in their “Proxy status”.

If one of these two records is missing from the list:

  1. Click the “Add record” button.
  2. Select the appropriate type for your hosting (most likely “A” or “CNAME”).
  3. As the “Name”, type “www” if you’re adding the www version, or “@” if you’re adding the non-www version.
  4. Type the relevant content (IP address or CNAME URL) provided by your hosting.

Create the page rule

Redirect www to non-wwww

  1. Under the “Rules” tab in the left menu, click on “Page Rules”.
  2. Click the “Create Page Rule” button.
  3. Under “If the URL matches”, type your www version of your domain followed by an asterisk (*): www.example.com* - change example.com to your domain.
  4. Under the “Pick a Setting” dropdown, select “Forwarding URL”.
  5. Under “Select status code”, select “302 - Temporary Redirect”.
  6. Under “Enter destination URL” - type the non-www version of your domain followed by $1 which will preserve the same path when redirecting: https://example.com/$1 - change exmple.com to your domain.
  7. Click the “Save and Deploy” button.

Redirect non-www to www

The same process as explained above applies also for redirecting from non-www to the www version, only with the values in reverse order:

  • Under “If the URL matches”, type the non-www version of your domain followed by an asterisk (*), example.com*.
  • Under “Enter destination URL”, type the www version of your domain followed by $1: https://www.example.com/$1.