Redirect root domain to www using CloudFlare

Redirect root domain to www using CloudFlare
Date
Tags
CloudFlare
DNS
Networking

Setup a redirect using CloudFlare to redirect requests from the root domain to the www subdomain.

Login to your CloudFlare account and select the domain you want to apply the redirect rule to. The free-tier plan is sufficient for this setup and allow us to setup 10 rules for free.

Goto “Rules” -> “Redirect rules” and create a new rule using the following settings:

  • Rule name: Redirect root to www
  • When incoming requests match: Custom filter expression
    • Field: Hostname
    • Operator: equals
    • Value: domain.com

Expression preview:

(http.host eq "domain.com")
  • Then
    • Type: Dynamic
    • Expression: concat("https://www.domain.com", http.request.uri.path)
    • Status code: 301
    • Preserve query string: Checked

Important

For the CloudFlare redirect rules to work you have to make sure that the DNS records for the root domain is proxied through CloudFlare. This is indicated by the orange cloud icon in the DNS records.

Test

Test the redirect rule using curl:

curl -i https://domain.com/en/test

HTTP/2 301
date: Sat, 02 Mar 2024 18:40:23 GMT
location: https://www.domain.com/en/test
cache-control: max-age=3600
expires: Sat, 02 Mar 2024 19:40:23 GMT
server: cloudflare

Redirect rules documentation

More Articles