How to redirect to an url to cretain url

I have a domain name xyz .com where when someone clicks on xyz.com/welcome it should redirect to the on.xyz.com/welcome(on.xyz.com is a subdomain)
and i am trying to do using this code but when i am using xyz.com/welcome then i am getting
Not Found

The requested URL was not found on this server.
here is the code using i am trying
addEventListener(‘fetch’, event => {
event.respondWith(fetchAndApply(event.request))
})

/**

  • Redirect if matches case
  • @param {Request} request
    */
    async function fetchAndApply(request) {
    // This extracts the path so you have a pattern to match
    var url = new URL(request.url);
    var path = url.pathname;
    var site = “http://xyz.com
    if(path ===‘http://xyz.com/welcome’)
    {
    return Response.redirect(‘http://on.xyz.com/welcome’, 301);
    }

}

Is there a reason you’re not using a Page Rule for this?

no but i don’t want to use page rules i wanted to do this using javascript only

Fair enough.

If you’re getting a Not Found for /welcome, then…did you add this Worker to a Route? If so, which Route?

If your goal is to apply this to the entire domain, but only redirect certain URLs, try this:

If it’s just for /welcome, then create a route for /welcome, then look at this example:

i have added this route http://xyz.com/welcome* and the worker is the above code which i mentioned in the question

If you assigned that Worker to that route, then you shouldn’t get a 404. The worker should execute. Either successfully, or with a Worker error.