Redirecting example.com to www.example.com when using Cloudflare workers sites

We are hosting a static site on Cloudflare workers and have HSTS enabled. However, I can not get example.com to redirect to www.example.com using page rules following the Cloudflare tutorial here:

A. Workers Routes

On workers we have the following routes pointing to our worker:

*example.com/*
example.com/
example.com/*

B. Domain DNS

On the domain DNS there are two A records proxied through Cloudflare.

The first A record points example.com to 192.2.0.1
The second A record points www to 192.2.0.1

Note I can not change the first record from example.com to @, simply as the Cloudflare DNS interface is changes @ to example.com when I save the record.

C. Page Rules

We have two rules, one for www redirect and one for caching everything.

The first rule:

https://example.com/* forwarding URL 302 temporary redirect to https://www.example.com/$1

The second rule: https://www.example.com/*, cache everything.

1 Like

The @ symbol is in this case equal to your root domain. For the routes pointing to the worker, you could remove example.com/ and example.com/*, as you want them to redirect to www. This should make the page rules for example.com work, too.

1 Like

Thanks for the feedback Tom, but that didn’t work. https is still not being redirected to https://www.

Per your suggestion, we have set up one worker route at *example.com/*

Then here are our two page rules, with the forwarding URL 301 redirect and the cache everything setting:

Our DNS A records for both @ and www proxied through cloudflare.

As far as HTTPS, we have

Always Use HTTPS (on)
HTTP Strict Transport Security (HSTS) (on - max age 6 months)

I’m kind of at a loss here.

2 Likes

Try changing your worker route to *.example.com/
That way there’s a dot in front that it needs to match, for www., and sub., etc. But won’t match example.com because that doesn’t start with a dot.

3 Likes

Thanks! that fixed it.

1 Like