【发布时间】:2022-08-21 01:16:56
【问题描述】:
我有兴趣根据用户的地理位置重定向用户。出于这个原因,我决定使用 Cloudflare Workers。我成功阅读并实施了Country Redirection on Workers,但还有一件事需要我解决。重定向工作 100% 并且一直工作,正如它应该做的那样。但是,理想情况下,我希望重定向仅在第一次访问时起作用,然后尊重语言会话。 here 也报告了此问题。解决方案似乎是使用适当的 cookie。更具体地说,其中一个 cmets 提到:“您可以使用 cookie,您在响应对象中设置,然后在请求对象中检查。”
如果有人能准确指出如何设置此 cookie 以实现我的目标并克服此问题,我将不胜感激。
非常感谢。
这是我的工人代码:
//these countries go to /sg
var sg_countries = [\'SG\', \'TH\', \'MY\', \'VN\', \'RI\', \'RP\', \'LA\', \'BN\'];
//these go to /jp
var jp_countries = [\'JP\'];
//these go to /gr
var gr_countries = [\'GR\'];
//these go to /kr
var kr_countries = [\'KR\'];
//these countries go to /zh-sg
var zh_sg_countries = [\'TW\', \'HK\', \'CN\'];
addEventListener(\'fetch\', event => {
event.respondWith(Redirect(event.request))
})
function inArray(needle, haystack) {
var length = haystack.length;
for (var i = 0; i < length; i++) {
if (haystack[i] == needle) return true;
}
return false;
}
function mapCountry(country_code) {
if (inArray(country_code, sg_countries)) {
return \'https://ofdreams.com/sg\';
}
if (inArray(country_code, jp_countries)) {
return \'https://ofdreams.com/jp\';
}
if (inArray(country_code, gr_countries)) {
return \'https://ofdreams.com/gr\';
}
if (inArray(country_code, kr_countries)) {
return \'https://ofdreams.com/kr\';
}
if (inArray(country_code, zh_sg_countries)) {
return \'https://ofdreams.com/zh-sg\';
}
//everyone else gets US
return \'https://ofdreams.com\';
}
/**
* Fetch and log a given request object
* @param {Request} request
*/
async function Redirect(request) {
var url = new URL(request.url);
console.log(\"This is URL\" + url);
correctHost = mapCountry(request.headers.get(\'CF-IPCountry\'));
console.log(\"This is correct Host\" + correctHost);
return new Response(\'\', {
status: 301,
headers: {
\'Location\': correctHost
}
})
}
标签: redirect cookies geolocation cloudflare cloudflare-workers