// Add a fetch event listener, which is triggered when a request is incoming. It uses the handleRequest function to handle requests and return responses.async function handleRequest(request) {// Define the target external host name.const yourExternalHostname = "www.example.com";// Create mapping from paths to redirect URLs.const redirectMap = new Map([["/foo", "https://" + yourExternalHostname + "/redirect1"],["/bar", "https://" + yourExternalHostname + "/redirect2"],["/baz", "https://" + yourExternalHostname + "/redirect3"],]);// Parse the request URL.const url = new URL(request.url);// Get the path part of the URL.const path = url.pathname;// Check whether the path is in the redirect mapping, and if so, perform a redirect.if (redirectMap.has(path)) {return Response.redirect(redirectMap.get(path), 301);} else {// If the path is not in the mapping, return a 404 status code.return new Response('Not Found', { status: 404 });}}// When a request event occurs, use the handleRequest function to handle it.addEventListener('fetch', event => {event.respondWith(handleRequest(event.request));});
https://www.example.com/redirect2
will be performed automatically.
Was this page helpful?