Hey @fool and @hrishikesh!
I hope you are both doing well.
Sorry for re-opening a (very) old thread. I figured out a solution for this and thought I would share it here in case you have any other customers in the future who run into something similar.
This is the Javascript that the customer would add to a Cloudflare Worker. Essentially what it does is whenever a site visitor hits the customer’s subdomain (i.e. blog.example.com), it will check if the request is from Netlify or a human. It does this by checking for the x-nf-site-id
request header, which as you both obviously know, Netlify sets in a redirect.
With this configuration, a user is able to have their main website / root domain (i.e. example.com) hosted by Netlify while also adding any other sites under it via a reverse proxy. For example, a blog they may have hosted on Ghost, Webflow, WordPress, etc.
There are two benefits to this configuration. The first being - SEO; by 301 redirecting your subdomain (blog.example.com) to your subdirectory (example.com/blog), search engines will only crawl and rank the latter one. The second benefit is users will be able to use Netlify Edge Functions and not have to worry about users bypassing them by accessing their blog through the subdomain instead.
const base = "YOUR-BASE-URL" // i.e. https://example.com/blog
const statusCode = 301
async function handleRequest(request) {
const url = new URL(request.url)
const isNetlifyReq = request.headers.get('x-nf-site-id'); // Check If Request Is From Netlify
if (!isNetlifyReq) { // If Not Netlify Request, Redirect To Base URL
const { pathname, search, hash } = url
let destinationURL = base + pathname + search + hash;
destinationURL = destinationURL.endsWith('/') ? destinationURL.slice(0, -1) : destinationURL; // Remove Trailing Slash (If Exists)
return Response.redirect(destinationURL, statusCode)
} else {
// If Netlify Request, Return Response
const response = await fetch(url);
return response;
}
}
addEventListener('fetch', event => {
event.respondWith(handleRequest(event.request));
});