How to Use CloudFlare to Redirect www to Non-www

How to Use CloudFlare to Redirect www to Non-www

·

2 min read

Have you ever needed to make sure your website works with both www and non-www versions?

I did too!

My website is served at https://thesshguy.com, but I also wanted https://www.thesshguy.com to work.

The Problem with Two Versions

The first thing I tried was to add A and AAAA DNS records for both versions. While that does work, there's a problem with this approach. Google and other search engines get confused because it looks like there are two versions of my website.

When Google tries to index my website, there's no clear answer to which is the canonical version.

So what can we do instead?

Improve Things with Redirects

Since we have two versions, we can redirect one to the other to improve things. This tells web crawlers which version is the main one. I used a Cloudflare rule to redirect the www version to the non-www version.

Note: I had to include DNS records and add a redirect rule for things to work correctly.

Here's how you can do it too.

Steps to Set Up the Redirect

Note: Make sure to use your own website in place of mine.

  1. Log into your Cloudflare account

  2. Go to Rules > Redirect Rules

    A menu displaying various rule options including "Rules," "Configuration Rules," "Transform Rules," "Redirect Rules" (highlighted), "Origin Rules," "Page Rules" (marked as Deprecated), and "Settings."

  3. Click Create rule under Single Redirects

  4. Name your rule (I named mine "WWW to Non WWW")

  5. Set up a custom filter like this:

    • Field: Hostname

    • Operator: equals

    • Value: www.thesshguy.com

    • URL redirect Type: dynamic

    • Expression: concat("https://thesshguy.com", http.request.uri.path)

    • Status Code: 301 (permanent redirect)

Here's what my rule looks like:

Screenshot of a web interface for creating a new dynamic redirect rule. The rule is named "WWW to Non WWW". The interface includes options for matching incoming requests, with a custom filter expression set to match the hostname "www.thesshguy.com". The redirect type is dynamic, with an expression to concatenate "https://thesshguy.com" with the request URI path. The status code for the redirect is set to 301.

And that's it!

Now your www version will redirect to the non-www version. Hopefully, this helps you set up your own Cloudflare redirects!