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)
}