Reverse proxies for multiple subdomains

I have an apex domain hosted on Cloudflare where my main company page is deployed: ourplatform.com

In the DNS settings, I have a couple of sub-domains that host additional offerings in separately deployed discrete applications:

  • chapters-foo.ourplatform.com
  • association-accessors-bar.ourplatform.com

What I am trying to accomplish is having the following:

ourplatform.com/chapters-foo point to chapters-foo.ourplatform.com, but show the user the former URL in their address bar.

The exact same thing should happen for our other service, whereby:

ourplatform.com/association-accessors-bar should point to association-accessors-bar.ourplatform.com, but should show the user the former URL in their address bar.

Furthermore, any subpaths like ourplatform.com/chapters-foo/chapters/2 should show the user the content of chapters-foo.ourplatform.com/chapters/2.

Through various posts here and elsewhere, I’ve gotten partially there, but am now rather stuck.

I have deployed a worker containing the following code:

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

async function handleRequest(request) {
  if (request.method !== "GET") {
    return new Response("Invalid method", { status: 405 });
  }

  const { pathname, search } = new URL(request.url);
  let targetUrl;

  if (pathname.startsWith("/chapters-foo")) {
    targetUrl = `https://chapters-foo.ourplatform.com${pathname.replace('/chapters-foo', '')}${search}`;
  } else if (pathname.startsWith("/association-accessors-bar")) {
    targetUrl = `https://association-accessors-bar.ourplatform.com${pathname.replace('/association-accessors-bar', '')}${search}`;
  } else {
    return new Response(`Invalid request`, { status: 404 });
  }

  const originRequest = new Request(targetUrl, request);
  originRequest.headers.set("Origin", new URL(targetUrl).origin);

  const response = await fetch(originRequest, {
    cf: {
      cacheTtl: 20,
      cacheEverything: true,
    },
  });

  return new Response(response.body, response);
}

And I have two Routes defined under that worker:

  • www.ourplatform.com/association-accessors-bar/*
  • www.ourplatform.com/chapters-foo/*

See screenshot:

Now comes the part where I’m stuck:

Visting ourplatform.com/chapters-foo/ shows that URL and I can even navigate to e.g. ourplatform.com/chapters-foo/chapters/2.

But visiting ourplatform.com/association-accessors-bar/ shows the original URL association-accessors-bar.ourplatform.com in the address bar.

So, despite setting the Routes identically under the worker, I’m seeing different behavior on the routes.

I’m not sure where my misunderstanding is. Is there a mistake in my worker code? Or have I improperly defined the two routes in the settings for the worker?

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