Page rule to redirect all URLs to root domain

I just deployed a one-page website to Cloudflare pages and added a rule to redirect www traffic to non-www:

www.mydomain.com/*
Forwarding URL (Status Code: 301 - Permanent Redirect, Url: https://mydomain.com/$1)

Now since it is one page, all random URLs like https://mydomain.com/dbdbj546 just show the homepage.

What redirect can I use to redirect other URLs to the root domain https://mydomain.com except for when it has URL tracking parameters?

So this URL shouldn’t be rewritten to root: ‘Web Hosting, Domain Name Registration - MyDomain.com

But https://mydomain.com/dbdbj546 should be

If I also add this it results in “too many redirects” when loading the page

mydomain.com/*
Forwarding URL (Status Code: 301 - Permanent Redirect, Url: https://mydomain.com)

www.mydomain.com/*
Forwarding URL (Status Code: 301 - Permanent Redirect, Url: https://mydomain.com)

That’s because it redirects https://mydomain.com/ to itself.

I’ve not tested these, but this should give you something to work with. This uses Redirect Rules instead of Page Rules.

First, redirect the www to the apex, including all the path and parameters…

Then redirect everything for the apex domain to the index page of the apex domain, unless the request is for the index page itself (to prevent “too many redirects”) or contains the URL tracking parameters (you’ll need to tweak things there to match what you want)…

Make sure you have a DNS record for www (a proxied dummy value of A 192.0.2.1 or AAAA 100:: will be ok as the whole subdomain is redirected).

2 Likes

Wow, rockstar thanks @sjr !

Works great

1 Like

I also had to set URI Path does not contain _astro and images because it was redirecting all the assets. Works well otherwise.

I don’t think the free Cloudflare account allows regex in redirects?

1 Like

This topic was automatically closed 2 days after the last reply. New replies are no longer allowed.