Redirect
This example forwards requests from one or more URLs to one or more other URLs.
Redirect all requests to a single URL
async fetch(request) {
const destinationURL = "https://example.com";
const statusCode = 301;
return Response.redirect(destinationURL, statusCode);
}
Redirect requests from one domain to another
addEventListener("fetch", (event) => {
event.respondWith(handleRequest(event.request));
});
async function handleRequest(request) {
const base = "https://example.com";
const statusCode = 301;
const url = new URL(request.url);
const { pathname, search } = url;
const destinationURL = `${base}${pathname}${search}`;
console.log(destinationURL);
return Response.redirect(destinationURL, statusCode);
}