Rewrite traffic based on hostname

I'm building a site with custom domains. I would like to have my base domain (base-example.com) render normally, but IF hostname !== base-example.com I want to render the content of base-example.com/api/custom-content?host=some-hostname.com - How can I do that? I use workers, but could switch to pages if needed.
1 Reply
raiyansarker
raiyansarker7mo ago
you can create an endpoint as you defined (/api/custom-content?host=some-hostname.com) and then in your index file, you can check the host header and depending on that, you can rewrite the traffic to the specified url. In order to rewrite the traffic, you can use the fetch function but fetch function won't accept relative url like this
// this won't work
fetch("/api/custom-content?host=some-hostname.com")
// this won't work
fetch("/api/custom-content?host=some-hostname.com")
. So you can prefix it with
fetch("http://internal/api/custom-content?host=some-hostname.com")
fetch("http://internal/api/custom-content?host=some-hostname.com")
and it would rewrite the url and render the page. Keep in mind that if the custom page for other domain contains many request for image, js or css, your worker might have to proxy that. In free plan, I believe the subrequest count is 50. You may not exceed it depending on how you handle these static assets. One more thing, you can setup 100 custom domains in the free plan using cloudflare pages, I am not sure the domain count on workers but you can use cloudflare for saas to create vanity domains.