Country redirection with request url

Hi

I’m using CloudFlare country redirection code, How can add url request to end of url.

for example
Visitor request url is https://de.example.com/test1/ but the script redirect to ttps://de.example.com/

CloudFlare country redirection code;

/**
 * Returns a redirect determined by the country code
 * @param {Request} request
 */
async function redirect(request) {
  // 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 await fetch(request)
  }
}
/**
 * A map of the URLs to redirect to
 * @param {Object} countryMap
 */
const countryMap = {
  US: "https://example.com/us",
  DE: "https://de.example.com/",
}

async function handleRequest(request) {
  return redirect(request)
}

addEventListener("fetch", event => {
  event.respondWith(handleRequest(event.request))
})

Are you trying to redirect to: example.com/de/test1?

If so, you see that countryMap in the code, this specifics where the redirects go. That’s why it goes to de.example.com

Side note: you probably want the pathname from the URL and append that to the redirection, currently it won’t do that.

1 Like

This topic was automatically closed 15 days after the last reply. New replies are no longer allowed.