Subdirectory and Internal Links using Cloudflare Worker

addEventListener('fetch', event => {
  var url = new URL(event.request.url);
  if (url.pathname.startsWith('/shop/') || url.pathname === '/shop') {
handleBlog(event, url);
  } else {
event.respondWith(fetch(event.request));
  }
})

async function handleBlog(event, url) {
  var originUrl = url.toString().replace(
'https://www.domain.com/shop',
   'https://alternate-server.com/shop');
  originUrl = originUrl.toString().replace(
'https://domain.com/shop',
   'https://alternate-server.com/shop');
  event.respondWith(fetch(originUrl, { cf: { cacheEverything: true } })); 
}

I’m trying to map the /shop subdirectory to another server and it works, except once you land on any page - i.e. /shop/ or /shop/product1.html all of the internal links are still linking to https://alternate-server.com/shop vs. domain.com/shop

I was previously using a nginx server and it was setup like this and the links mapped appropriately -

location /shop/ {
	proxy_pass https://alternate-server.com/shop/;
	proxy_set_header Host              $host;
	proxy_set_header X-Forwarded-For   $proxy_add_x_forwarded_for;
	proxy_set_header X-Forwarded-Proto $scheme;
}

I’ve been banging my head against the wall. Any help is very much appreciated!

1 Like

What you currently are doing is simply rerouting the request. If you still have the previous hostnames in your links you will use absolute URLs instead of relative ones.

The best approach would likely be to switch to relative URLs. If that is not possible, you will also have to tamper with the content.

Is there anyway to fix this issue without updating the second server? I don’t have direct access to the server and was hoping this was something I could fix with a worker.

Second server? Which is?

As I mentioned in my response, either fix it on the original server (which is preferable) or use a worker to replace all links in the response body.

Second server is the alternate-server.com - the one we’re showing behind the masked url at domain.com/shop.

Do you have an example of how to replace the links in the response body? Does that really effect performance?

Right, confused it. Yes, you will have to change that on the second server then.

Search for worker examples here on the forum, which modify the response body. That should get you started.

Again, I’d recommend to rather change that on the server.

1 Like