V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
Alan3
V2EX  ›  程序员

如何通过 cloudflare worker 实现假装关闭网站?

  •  
  •   Alan3 · 349 天前 · 976 次点击
    这是一个创建于 349 天前的主题,其中的信息可能已经有所发展或是发生改变。

    需求: 国内 ip 访问网站显示正在维护中,非大陆 ip 正常访问。

    1. 使用 WAF ,直接设置来自 China 的 ip 阻止。 但是他显示的页面是 cloudflare 的禁止访问的页面,不太符合需求。

    2. 使用 worker ,用以下的代码部署, 来自大陆的 ip 能正常阻止,但是非大陆 ip 会一直重定向:

    export default {
      async fetch(request, env) {
        let country = request.headers.get('cf-ipcountry')
    
        if(country === 'CN') {
          return new Response('Sorry, this page is not available.', { status: 403 })
        }
    
        return fetch(request)
      }
    }
    
    

    请教一下大家有什么解决方法没有? (我并不专注于 js 和网络,所以有什么我需要了解的知识,还请不吝指出,我去了解,谢谢)

    wdssmq
        1
    wdssmq  
       349 天前
    export default {
    async fetch(request, env) {
    let country = request.headers.get('cf-ipcountry')

    if (country === 'CN') {
    return new Response('Sorry, this page is not available.', { status: 403 })
    }

    // 获取请求的 URL
    const reqUrl = request.url;
    // 获取 path
    const path = new URL(reqUrl).pathname;
    // 真实请求的 URL
    const realUrl = 'https://www.baidu.com' + path;

    return fetch(realUrl)
    }
    }
    Alan3
        2
    Alan3  
    OP
       349 天前
    @wdssmq #1 谢谢你的回复,但我找到问题所在了,并不是 worker 的代码问题造成的重定向次数过多。最后通过这个重定向解决参考: https://shenghuahuancai.cn/posts/%E4%BD%BF%E7%94%A8CloudFlare%E5%AF%BC%E8%87%B4%E7%BD%91%E7%AB%99%E9%87%8D%E5%AE%9A%E5%90%91%E7%9A%84%E6%AC%A1%E6%95%B0%E8%BF%87%E5%A4%9A%E8%A7%A3%E5%86%B3%E6%96%B9%E6%A1%88/ ,worker 代码并未做改动
    wdssmq
        3
    wdssmq  
       349 天前
    @Alan3 好吧。。我一直把 worker 当单独的反代使用,大概是也能当 CDN 的前置处理??毕竟是他们自家的产品。。
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   5145 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 25ms · UTC 03:52 · PVG 11:52 · LAX 20:52 · JFK 23:52
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.