Worker code for workaround to redirect pages with multi-level paths
I've been trying to set up a redirect for a list of URLs with multi-level paths to another multi-level path through the GHL platform, this hasn't been working out so I am now trying a worker workaround in which I input the following code:
addEventListener('fetch', event => {
event.respondWith(handleRequest(event.request))
})
async function handleRequest(request) {
const url = new URL(request.url)
// Match specific paths or full URIs
if (
url.pathname === '/collections/hoodies'
url.pathname === '/collections/hoodies?page=1'
url.pathname === '/collections/hoodies?page=2' ||
request.url === 'https://exampledomain.com/collections/hoodies'
) {
// Redirect to the new URL
return Response.redirect('https://exampledomain.com/products-list/collections/hoodies', 301)
}
// If the request doesn't match, pass it through
return fetch(request)
}
I am currently getting this error when visiting the worker page: There is nothing here yet
If you expect something to be here, it may take some time.
Please check back again later.
8 Replies
Hello! Are you running this Worker on workers.dev or routed on a zone?
Hello! It is running on worker.dev
So for " If the request doesn't match, pass it through", there is no origin for workers.dev, so it is hitting the workers.dev 404 page. What do you want that path to do?
I've been having issues using the redirect rules due to using GHL platform, which isn't allowing rederict to or from multi-level paths, I was advised to try a workaround on worker.dev to do this. I am trying to redirect these paths:
url.pathname === '/collections/hoodies'
url.pathname === '/collections/hoodies?page=1'
url.pathname === '/collections/hoodies?page=2'
All from the same domain to this path: /products-list/collections/hoodies
The redirect should work correctly, it is the case of calling fetch(request) on workers.dev without changing the url that will result in the 404 page.
For example, https://misty-rain-fc5d.taylorlee.workers.dev/redirect redirects with 301 to example.com, whereas https://misty-rain-fc5d.taylorlee.workers.dev does fetch(request) and thus returns the 404 page. If you are trying to fetch the origin server of a website that you own, you may need to use a Route instead of workers.dev https://developers.cloudflare.com/workers/configuration/routing/
Cloudflare Docs
Routes and domains | Cloudflare Workers docs
Connect your Worker to an external endpoint (via Routes, Custom Domains or a
workers.dev
subdomain) such that it can be accessed by the Internet.Does that make sense?
Yeah, I'm trying to piece it together, I'm sorta new to this 😅 From what I see on the doc about routes I'd need to add a trigger event and route in the settings, right?
Well... actually, I see on the doc it said Settings > Trigger > Route, but it seems it should be on Settings > Domains & Route > Route, right?