Hi there, I am using Cloudflare Worker to proxy info from another website and create routes. It’s work great, but redirects doesn’t works. Here is my code. Can somebody please help me?
const DOMAIN = ‘site1’;
const PROXYPATH = ‘proxy-category’;
const ORIGIN = ‘site2/category’;
addEventListener(‘fetch’, event => {
var url = new URL(event.request.url);
if (url.pathname.startsWith(’/’ + PROXYPATH + ‘/’) || url.pathname === ‘/’ + PROXYPATH) {
handleRequest(event, url);
} else {
event.respondWith(fetch(event.request));
}
})
async function handleRequest(event, url) {
// Change URL from public URL to use the origin URL
var originUrl = url.toString().replace(
‘https://’ + DOMAIN + ‘/’ + PROXYPATH,
‘https://’ + ORIGIN
);
event.passThroughOnException();
event.respondWith(fetch(originUrl));
}
async function handleEvent(event) {
const url = new URL(event.request.url)
// Redirects
const redirects = {
‘/category/subcategory/’: ‘/category/subcategory’,
}
for (const source in redirects) {
if (url.pathname.includes(source)) {
const target = new URL(url.href.replace(source, redirects[source]))
return Response.redirect(target, 301)
}
}
// Rest of the code to handle all other requests
}