Wildcard Domain / Subdomain Redirect

Hello,

I researched the internet and the CF community but couldn’t find a working example.

I have registered four domains, the 1st one is primary domain and the rest are the variants of the primary. Whatsoever, I will be using the primary domain at all the times. So no matter whatever variant people type in the URL bar, they will always land at the primary domain. People could type any combination of domain, subdomain, destination page or even all.

Primary domain: axxxxxy .com
Variant domain names: axxxxxi .com, aaxxxxxy .com, aaxxxxxi .com

I believe the workflow would be something like this:

  1. Add a wildcard A record for all domains.

  2. Add a page rule in all the variant domains.

The page rule that I am looking for should redirect as below:

variant-domain .com/* >>> primary-domain .com/*
.variant-domain .com/ >>> .primary-domain .com/

I am not sure if this is what I would add:

variant-domain .com/ >>> $1primary-domain .com/$2

I would appreciate if someone could help me out with this.

Thanks in advance

This won’t work unfortunately. In order for forwarding to work, you need to use Page Rule. For Page Rule to work, traffic need to pass through CloudFlare. But your requirement of any sub domain need a wildcard dns, and wildcard dns is DNS only(show a grey icon in cloudflare dns).

You should look into running a simple Nginx proxy or cloudflare worker to redirect yourself.

1 Like

Hi there,

Thank you for your reply.

I will look into the solution you mentioned.

I came across the following code, but a little confused if it will redirect any requests from either the base domain or the subdomain irrespective of the destination page to the another domain or subdomain.

const base = "https://example.com"
const statusCode = 301

async function handleRequest(request) {
  const url = new URL(request.url)
  const { pathname, search } = url

  const destinationURL = base + pathname + search

  return Response.redirect(destinationURL, statusCode)
}

addEventListener("fetch", async event => {
  event.respondWith(handleRequest(event.request))
})

That looks like code for Cloudflare Workers, which also needs to be a :orange: Proxied hostname.

If I were to want to do this, my domain registrars allow for domain forwarding. Anything in one domain would forward to a specific URL I set.

Oh, I get it now.

Thanks :slight_smile:

1 Like