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
- Log in to your Cloudflare account.
- On the Cloudflare homepage, click on the desired site.
- Click the “DNS” tab in the left menu.
- 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:
- Click the “Add record” button.
- Select the appropriate type for your hosting (most likely “A” or “CNAME”).
- As the “Name”, type “www” if you’re adding the www version, or “@” if you’re adding the non-www version.
- Type the relevant content (IP address or CNAME URL) provided by your hosting.
Create the page rule
Redirect www to non-wwww
- Under the “Rules” tab in the left menu, click on “Page Rules”.
- Click the “Create Page Rule” button.
- Under “If the URL matches”, type your www version of your domain followed by an asterisk (*):
www.example.com*
- changeexample.com
to your domain. - Under the “Pick a Setting” dropdown, select “Forwarding URL”.
- Under “Select status code”, select “302 - Temporary Redirect”.
- 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
- changeexmple.com
to your domain. - 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
.