Country based routing through workers not redirecting the internal pages

my main domain is www.example.com i need to redirect to www.example.com/in (for india) and www.example.com/ae (for uae) based on geo location routing using workers in cloudflare.

So i added a route www.example.com and given the below script in workers

export default {
async fetch(request) {
/**
* A map of the URLs to redirect to
* @param {Object} countryMap
*/
const countryMap = {
IN: "https://www.example.com/in/",
AE: "https://www.example.com/ae/",
};

  // Use the cf object to obtain the country of the request
  // more on the cf object: https://developers.cloudflare.com/workers/runtime-apis/request#incomingrequestcfproperties
  const country = request.cf.country;

  if (country != null && country in countryMap) {
    const url = countryMap[country];
    return Response.redirect(url);
  } else {
    return fetch(request);
  }
},

};

The redirection is working based on country but when we call www.example.com/pricing (Like this some pages are there) directly its not redirecting to www.example.com/in and its internal pages(Like www.example.com/in/pricing , www.example.com/in/aboutus). Can any one have any idea about it?

Hi,

You could easily set your redirection with a single dynamic Redirect Rule, since redirects trigger before Workers routes.

When incoming requests match...
(http.host eq "example.com" 
and ir.src.country equals "IN" 
and not starts_with(http.request.uri.path, "/in")

Then

URL Redirect 
Type: Dynamic
Expression: concat("https://example.com/in", http.request.uri.path)
Preserve query string: yes.

If you’d rather want to fix your Worker code, a better place to ask for help or :search: for a solution would be the Cloudflare Developers Discord channel.