Loading... 因为一些原因将旧博客移转到了国外,为了更加省事打算直接屏蔽中国大陆的访问,不想耗费资源在VPS上面用GeoIP模块去实现,也不想用国内公司的相关服务(比如阿里云云解析的分国家地区解析、腾讯云CDN根据国家屏蔽访问等) 我最终选择了国外大厂Cloudflare的免费服务,下图是 HTTP 请求通过 Cloudflare 配置代理时流量序列:  Cloudflare免费用户好像已经无法自定义阻断页面了、也无法自定义403错误页了,不过好在还有Workers可以免费使用:  首先创建一个Workers,选择“从 Hello World! 开始”,名称随便、比如我用的是“blockcn”,内容不动直接部署,然后进入这个Worker点击右上方的图标编辑代码,输入如下代码: ``` addEventListener('fetch', event => { event.respondWith(handleRequest(event.request)) }) async function handleRequest(request) { try { // 获取访问者国家(Cloudflare提供的CF-IPCountry头) const country = request.headers.get('CF-IPCountry') // 处理国家代码为空的情况(极少数情况) if (!country) { // 可以选择允许访问或拒绝,这里选择允许 return fetch(request, { cf: { // 可选:指定缓存行为 cacheTtl: 300 } }) } // 若为中国大陆用户(CN),返回阻断页面 if (country === 'CN') { return new Response(` <!DOCTYPE html> <html lang="zh-CN"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>访问受限</title> <style> body { font-family: "Microsoft YaHei", sans-serif; margin: 0; padding: 0; min-height: 100vh; background-color: #f0f2f5; display: flex; justify-content: center; align-items: center; } .container { text-align: center; background: white; padding: 3rem; border-radius: 10px; box-shadow: 0 4px 20px rgba(0,0,0,0.1); } h1 { color: #e53e3e; margin-bottom: 1rem; font-size: 2rem; } p { color: #4a5568; font-size: 1.1rem; max-width: 500px; margin: 0.8rem auto; } </style> </head> <body> <div class="container"> <h1>禁止中国大陆访问</h1> <p>抱歉!检测到你来自中国大陆,中断本次访问</p> <p>2025年8月之前内容只对大陆之外的访客开放</p> </div> </body> </html> `, { status: 403, // 403表示禁止访问 statusText: 'Forbidden', headers: { 'Content-Type': 'text/html; charset=utf-8', 'Cache-Control': 'no-store, no-cache, must-revalidate', // 禁止缓存阻断页面 'Pragma': 'no-cache' } }) } // 非中国大陆用户,代理到目标域名 // 构建完整URL(包含查询参数) const url = new URL(request.url) const targetUrl = new URL(url.pathname + url.search, 'https://www.yaohonglou.de') // 继承原请求的方法、头信息和body const response = await fetch(targetUrl.toString(), { method: request.method, headers: request.headers, body: request.body, redirect: 'follow', // 跟随重定向 cf: { // 可选:设置缓存策略 cacheTtl: 300, // 缓存5分钟(仅对GET请求有效) cacheEverything: true // 缓存所有符合条件的请求 } }) return response } catch (error) { // 捕获并处理所有可能的错误 return new Response(`请求处理错误: ${error.message}`, { status: 500, headers: { 'Content-Type': 'text/plain; charset=utf-8' } }) } } ``` 然后进入到域名页面,添加“Workes 路由”保存即可,具体参考下图:  如果大陆用户要绕过 Cloudflare 的阻断正常访问网站,其实也是有办法的: 1、优雅一点:翻墙使用境外IP访问站点 2、粗暴一点:修改本机hosts指向源站IP 最后修改:2025 年 09 月 21 日 © 允许规范转载 打赏 赞赏作者 支付宝微信 赞 如果觉得我的文章对你有用,请随意赞赏 本文作者:姚洪楼 短链地址:http://u5.hk/3 文章标题:Cloudflare 阻断大陆访客并自定义提示页面 版权属于:Yaohonglou.Com,转载请保留本文地址 u5.hk/3