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?
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.com → example.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);
}