Workers Use Case

Hey Community! I have one problem and I just want to know if this is case Workers can solve, I have zero knowledge about the topic… the said my case goes a follow:

I have a marketing website hosted in webflow, it runs in:
www.mycompany.com

I have a service which runs in:
mycompany.com/service_name

this service can run different pages, so right now I want to do something like:
mycompany.com/service_name/some_page/{id}

I can do www.mycompany.com/service_name/some_page/{id} and it will redirect to the naked domain mycompany.com/service_name/some_page/{id}

All good, but for SEO purposes I need to be able to serve the pages in: www.mycompany.com/service_name/some_page/{id} no mycompany.com/service_name/some_page/{id} so I need to take redirect out of the table.

So my question… is this something I can solve with workers?

I’ve been reading docs and this article, in particular, https://blog.cloudflare.com/diving-into-technical-seo-cloudflare-workers/ which gives some info but no the one I’m looking for.

Any ideas?

Yes, this is a great use-case for Workers!

Here is some code that should work (note, I haven’t tested it). It will check if the request starts with /service (so someone is trying to access that) and then it will change the hostname of the request (www.example.comexample.com) and fetch the resource to return it. This should work fine but let me know if you have any problems!

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

async function handleRequest(request) {
  const url = new URL(request.url);

  // If the request starts with '/service' then we want to serve from the apex domain not www.
  if (url.pathname.startsWith('/service')) {
    url.hostname = 'example.com'; // Apex domain
    return fetch(url);
  }

  // Serve the request as normal
  return fetch(request);
}
1 Like

woaaah! Walshy thank you so much for your kind answer!! I will take a look at the code, thanks for the help!! have a great weekend!

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