界泠博客

欢迎,这里是「泠」的界限。

利用 Cloudflare Workers 实现根据访客来源返回不同内容

泠's Avatar 2022-04-30 teach

3月前的博文,将其搬运到此。


这个方法可以屏蔽来自特定国家的访问请求,能做什么请自行发挥~~

(自己昨天突发奇想弄的,由于没有什么基础,代码都是七拼八凑的…)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
const blocked_region = ['CN'] // 屏蔽的国家代码

const text = `` // html源码放这


async function fetchAndApply(request) {
const region = request.headers.get('cf-ipcountry').toUpperCase();

if (blocked_region.includes(region)) {
response = new Response('Access denied: This page is not available in your region yet.', { // 返回错误提示
status: 403
});
} else{
response = new Response(text, {
headers: {
'Content-Type': 'text/html; charset=utf-8'
}
});
}
return response;
}

addEventListener('fetch', event => {
event.respondWith(fetchAndApply(event.request).catch(err => {
console.error(err);
new Response(JSON.stringify(err.stack), {
status: 500,
headers: {
'Content-Type': 'application/json'
}
});
}));
})
本文最后更新于 天前,文中所描述的信息可能已发生改变