Redirect www subdomain with Cloudflare

June 17, 2024

I wanted to run Google Ads for one of my side projects, but I noticed a problem: Google was displaying my domain as www.example.com, even though I hadn’t set up a www subdomain. This meant that if anyone tried to visit www.example.com, they’d find nothing. Since I’m not using a reverse proxy and rely on Cloudflare (CF) rules to direct traffic, I figured the best solution was to set up the www subdomain and handle everything on the Cloudflare side.

Here’s how I did it:

Setting Up the www Subdomain

  1. Log in to Cloudflare: First, I logged in to my Cloudflare account.
  2. Add the www Subdomain:
    • Navigate to the DNS settings.
    • Add a new DNS record with the following details:
      • Type: CNAME or A (depending on your setup)
      • Name: www
      • Target/Value: Your application’s IP address or main domain
    • Proxy Status: Ensure that the proxy is enabled (orange cloud icon). If the proxy is not enabled, Cloudflare won’t be able to manage the traffic.

Creating a Page Rule

  1. Navigate to Page Rules:
    • Go to the “Rules” section in Cloudflare.
    • Click on “Page Rules”.
    • Create a new page rule.
  2. Set Up the Redirect:
    • URL Pattern: Set the URL pattern to www.example.com/*. This pattern catches all URLs starting with www.example.com.
    • Settings: Choose “Forwarding URL” from the drop-down menu.
    • Status Code: Select either a 301 (permanent) or 302 (temporary) redirect.
    • Destination URL: Enter https://example.com/$1. The $1 ensures that any subdirectory path from the original URL is appended to the new URL.

By following these steps, any request to www.example.com will be seamlessly redirected to example.com, preserving any subdirectory paths.