Redirect Worker Script not redirecting

I am trying to redirect any URLs that contain a list of strings to the same URL with the string replaced to something else.

Examples:
www.abc.com/red/ --> www.abc.com/blue/
www.abc.com/something/green/cars/ --> www.abc.com/something/yellow/cars/

I can get the URL that the request should redirect to but can’t get it to actually redirect. Any guidance would be greatly appreciated.

addEventListener("fetch", event => {
  event.respondWith(fetchAndApply(event.request))
})

async function fetchAndApply(request) {
  // Read request URL.
  const url = new URL(request.url)
  // Array of items to redirect - ["FIND", "REPLACE WITH"]
  var stringsToRedirect = [
      //["FIND", "REPLACE WITH"]
      ["/red/", "/blue/"],
      ["/green/", "/yellow/"],
    ];
  // Check for the strings.
  stringsToRedirect.forEach(function(item) {
    if (url.href.indexOf(item[0]) > -1) {
      // console.log('* * * FOUND item: ' + item[0] + ' --> ' + item[1])
      var newURL = new URL(url.href.split(item[0]).join(item[1]))
      // console.log('REDIRECT TO: ' +  newURL)
      return new Response('',
      {
        status: 301,
        headers: {
          'location': newURL
        }
      })
    }
  });
  return fetch(request)
}

Here you go :slight_smile:

Simplified, tested and working:

addEventListener("fetch", event => {
  event.respondWith(fetchAndApply(event.request))
});

async function fetchAndApply(request) {
  // Read request URL.
  let url = request.url;
  // Array of items to redirect - ["FIND", "REPLACE WITH"]
  const stringsToRedirect = [
    //["FIND", "REPLACE WITH"]
    ["/red/", "/blue/"],
    ["/green/", "/yellow/"],
  ];
  // Check for the strings.
  stringsToRedirect.forEach(function (item) {
    if (url.indexOf(item[0]) > -1) {
      url = url.split(item[0]).join(item[1]);
    }
  });

  if (url !== request.url) {
    return new Response('', { status: 301, headers: { 'Location': url } });
  } else {
    return fetch(request);
  }
}

One of the issue in your script was that you were setting URL Object instead of String as Location header.

2 Likes

Awesome. Thank you! :+1: Works great.
I knew I was close but just couldn’t see the issue. Another set of eyes always helps.
Appreciate your help!

2 Likes