Performing Redirect Based on the Request Location
This sample determines the client's region and automatically redirects the client to the target URL of that region. It implements request distribution through edge functions based on the client's region.
Sample Code
// All region URL setsconst urls = {CN: 'https://www.example.com/zh-CN',US: 'https://www.example.com/en-US',};// Default redirect URLconst defaultUrl = 'https://www.example.com/en-US';/*** Redirect to the target URL based on the region of the current request* @param { Request } request*/function handleRequest(request) {// Get the region of the current requestconst alpha2code = request.eo.geo.countryCodeAlpha2;// Redirect target URLconst url = urls[alpha2code] || defaultUrl;return Response.redirect(url, 302);}addEventListener('fetch', event => {event.respondWith(handleRequest(event.request));});
Sample Preview
Enter a URL that matches an edge function trigger rule in the browser address bar to preview the sample effect.
