Country based redirection not working

Hello,

I’m trying to redirect the visitors from USA to my .com website to the .us website with a worker.js but it’s not working.

I don’t understand why it’s not working because while editing the worker I see the 302 code and an orange dot, I also see the following message on the console:

Based on US-based request, your user would go to https://aaaunbranded.us.

I’m using this code that I found in the docs:

export default {
  async fetch(request) {
    /**
     * A map of the URLs to redirect to
     * @param {Object} countryMap
     */
    const countryMap = {
      US: "https://aaaunbranded.us",
    };

    // 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];
      console.log(`Based on ${country}-based request, your user would go to ${url}.` )
      return Response.redirect(url);
    } else {
      return fetch("https://aaaunbranded.com", request);
    }
  },
};

Please let me know if it’s correct or I need to change something. Thank you very much.

Is there any reason you are using Workers and not a Single redirect.

You could filter if country is US and Hostname is not aaaunbranded.us then redirect to https://aaaunbranded.us

Matt

1 Like

Hi mbullock, thank you for your reply. I didn’t know about Single Redirects, I thought that the only way to do this was through workers.

I’ll try with single redirects and then I’ll let you know if it works.

1 Like

Hi mbullock, It’s the first time I try the single redirect, is this configuration correct?

Use “OR” instead of “AND” (a user can’t be in North America AND South America at the same time).

1 Like

Thank you so much, I did the correction you suggested me, so now it should work.

1 Like

Hello everyone,

I set the rule but a contact in the US told me that’s not working, can you please check if it’s set correctly? Or if there could be any reason why it’s not working?

Also I would like to ask you if there is some time to wait before the rule actually start to work.

Please let me know if you can help me.

What is the domain you are redirecting from?

Hi sjr,

the domain I’m redirecting from is [Preformatted text](http://aaaunbranded.com)

Maybe I should use “Country” instead of “Continent”?

aaaunbranded.com is not proxied through Cloudflare, so requests can’t be redirected by Cloudflare…
https://cf.sjr.org.uk/tools/check?dbff89d7e4f74073af4a727243222a45#dns

You’ll need to change the DNS record for aaaunbranded.com from “DNS only” to “proxied” for the redirect rule to run.

Ok, thank you for letting me know that, I’ll make the changes. Thank you so much.