搜 索

使用cloudflare反向代理解决iframe嵌套跨越问题

  • 1.2k阅读
  • 2023年04月08日
  • 2评论

前言

 最近使用VuePress Theme Hope搭建了一个站点把羽雀的内容搬到我自己的搭建的VuePress Theme Hope上面来,正好这几天 Apple的天气服务G了,然后有大佬发了一个Apple服务系统运行的状态监控
 然后我就想着把Apple服务监控也搬到我自己搭建的VuePress Theme Hope上面来,也方便我后续使用的时候直接看,使用iframe直接简单粗暴嵌套进去

Apple 服务状态监控


 然而没那么简单就能直接iframe嵌套进去,现在会为了防止种种问题都设置了跨越,我也尝试了一下果然是直接提示fused to display 'https://xxx.com/' in a frame because it set 'X-Frame-Options' to 'deny'.跨域咯~ 既然这样就解决一下吧

解决问题

 遇到跨越了我们就解决一下子,在手里悟了几天,然后找大佬帮忙解决了 简单粗暴~开始用准备用vercel的,后来换成了cloudflare,最后发现还是cf简单粗暴哈哈,不过使用cf是需要自己有一个域名的嗷,因为cf默认自带的域名被墙了无法访问.

前提条件

  • 自备一个域名
  • 能访问cloudflare
  • 拿到代码,代码下面我已经贴出来了,到时候自己改改即可

通用反向代理代码
修改第 2,6,18, 这三行的链接,改你需要反向代理的,例如我需要反向代理 www.apple.com 我就写 www.apple.com,不要要请求头哦就是HTTP HTTPS 这样的

// Website you intended to retrieve for users.
const upstream = 'example.com'
// Custom pathname for the upstream website.
const upstream_path = '/'
// Website you intended to retrieve for users using mobile devices.
const upstream_mobile = 'example.com'
// Countries and regions where you wish to suspend your service.
const blocked_region = []
// IP addresses which you wish to block from using your service.
const blocked_ip_address = []
// Whether to use HTTPS protocol for upstream address.
const https = true
// Whether to disable cache.
const disable_cache = false
// Replace texts.
const replace_dict = {
    '$upstream': '$custom_domain',
    '//example.com': ''
}
addEventListener('fetch', event => {
    event.respondWith(fetchAndApply(event.request));
})
async function fetchAndApply(request) {
    const region = request.headers.get('cf-ipcountry');
    const ip_address = request.headers.get('cf-connecting-ip');
    const user_agent = request.headers.get('user-agent');
    let response = null;
    let url = new URL(request.url);
    let url_hostname = url.hostname;
    if (https == true) {
        url.protocol = 'https:';
    } else {
        url.protocol = 'http:';
    }
    if (await device_status(user_agent)) {
        var upstream_domain = upstream;
    } else {
        var upstream_domain = upstream_mobile;
    }
    url.host = upstream_domain;
    if (url.pathname == '/') {
        url.pathname = upstream_path;
    } else {
        url.pathname = upstream_path + url.pathname;
    }
    if (blocked_region.includes(region)) {
        response = new Response('Access denied: WorkersProxy is not available in your region yet.', {
            status: 403
        });
    } else if (blocked_ip_address.includes(ip_address)) {
        response = new Response('Access denied: Your IP address is blocked by WorkersProxy.', {
            status: 403
        });
    } else {
        let method = request.method;
        let request_headers = request.headers;
        let new_request_headers = new Headers(request_headers);
        new_request_headers.set('Host', upstream_domain);
        new_request_headers.set('Referer', url.protocol + '//' + url_hostname);
        let original_response = await fetch(url.href, {
            method: method,
            headers: new_request_headers
        })
        connection_upgrade = new_request_headers.get("Upgrade");
        if (connection_upgrade && connection_upgrade.toLowerCase() == "websocket") {
            return original_response;
        }
        let original_response_clone = original_response.clone();
        let original_text = null;
        let response_headers = original_response.headers;
        let new_response_headers = new Headers(response_headers);
        let status = original_response.status;
        
        if (disable_cache) {
            new_response_headers.set('Cache-Control', 'no-store');
        }
        new_response_headers.set('access-control-allow-origin', '*');
        new_response_headers.set('access-control-allow-credentials', true);
        new_response_headers.set('x-frame-options', "ALLOW")
      
        new_response_headers.delete('content-security-policy');
        new_response_headers.delete('content-security-policy-report-only');
        new_response_headers.delete('clear-site-data');
        
        if (new_response_headers.get("x-pjax-url")) {
            new_response_headers.set("x-pjax-url", response_headers.get("x-pjax-url").replace("//" + upstream_domain, "//" + url_hostname));
        }
        
        const content_type = new_response_headers.get('content-type');
        if (content_type != null && content_type.includes('text/html') && content_type.includes('UTF-8')) {
            original_text = await replace_response_text(original_response_clone, upstream_domain, url_hostname);
        } else {
            original_text = original_response_clone.body
        }
        
        response = new Response(original_text, {
            status,
            headers: new_response_headers
        })
    }
    return response;
}
async function replace_response_text(response, upstream_domain, host_name) {
    let text = await response.text()
    var i, j;
    for (i in replace_dict) {
        j = replace_dict[i]
        if (i == '$upstream') {
            i = upstream_domain
        } else if (i == '$custom_domain') {
            i = host_name
        }
        if (j == '$upstream') {
            j = upstream_domain
        } else if (j == '$custom_domain') {
            j = host_name
        }
        let re = new RegExp(i, 'g')
        text = text.replace(re, j);
    }
    return text;
}
async function device_status(user_agent_info) {
    var agents = ["Android", "iPhone", "SymbianOS", "Windows Phone", "iPad", "iPod"];
    var flag = true;
    for (var v = 0; v < agents.length; v++) {
        if (user_agent_info.indexOf(agents[v]) > 0) {
            flag = false;
            break;
        }
    }
    return flag;
}

async function handleRequest(request) {
  return new Response(html, {
    headers: {
      "content-type": "text/html;charset=UTF-8",
    },
  })
}

addEventListener("fetch", event => {
  return event.respondWith(handleRequest(event.request))
})

uptimerobot监控代码
uptimerobot修改的位置分别是第4行和第22行

  • 第4行:const upstream_path = '/7w9kmszqLQ',这个 7w9kmszqLQ改成你自己uptimerobot监控预览界面的那一串
  • 第22行:改url=里面的内容改成你自己使用cloudflare反向代理后的链接
// Website you intended to retrieve for users.
const upstream = 'stats.uptimerobot.com'
// Custom pathname for the upstream website.
const upstream_path = '/7w9kmszqLQ'
// Website you intended to retrieve for users using mobile devices.
const upstream_mobile = 'stats.uptimerobot.com'
// Countries and regions where you wish to suspend your service.
const blocked_region = []
// IP addresses which you wish to block from using your service.
const blocked_ip_address = []
// Whether to use HTTPS protocol for upstream address.
const https = true
// Whether to disable cache.
const disable_cache = true
// Replace texts.
const replace_dict = {
    '$upstream': '$custom_domain',
    '//stats.uptimerobot.com': ''
}

const redirect = `<html>
<meta http-equiv="refresh" content="0;url=这里设置你使用cloudflare反向代理后的链接,例如:https://time.xx.com">
</html>>`;

addEventListener('fetch', event => {
    event.respondWith(fetchAndApply(event.request));
})
async function fetchAndApply(request) {
    const region = request.headers.get('cf-ipcountry');
    const ip_address = request.headers.get('cf-connecting-ip');
    const user_agent = request.headers.get('user-agent');
    let response = null;
    let url = new URL(request.url);
    let url_hostname = url.hostname;
    if (https == true) {
        url.protocol = 'https:';
    } else {
        url.protocol = 'http:';
    }
    if (await device_status(user_agent)) {
        var upstream_domain = upstream;
    } else {
        var upstream_domain = upstream_mobile;
    }
    url.host = upstream_domain;
    const path = url.pathname;
    if (url.pathname == '/') {
        url.pathname = upstream_path;
    }
    else if (url.pathname.includes('/api')) {
        url.pathname = url.pathname;
    }
    else if (url.pathname.includes('/assets')) {
        url.pathname = url.pathname;
    }
    else {
        url.pathname = upstream_path + url.pathname;
    }
    if (blocked_region.includes(region)) {
        response = new Response('Access denied: WorkersProxy is not available in your region yet.', {
            status: 403
        });
    } else if (blocked_ip_address.includes(ip_address)) {
        response = new Response('Access denied: Your IP address is blocked by WorkersProxy.', {
            status: 403
        });
    } else {
        let method = request.method;
        let request_headers = request.headers;
        let new_request_headers = new Headers(request_headers);
        new_request_headers.set('Host', upstream_domain);
        new_request_headers.set('Referer', url.protocol + '//' + url_hostname);
        let original_response = await fetch(url.href, {
            method: method,
            headers: new_request_headers
        })
        connection_upgrade = new_request_headers.get("Upgrade");
        if (connection_upgrade && connection_upgrade.toLowerCase() == "websocket") {
            return original_response;
        }
        let original_response_clone = original_response.clone();
        let original_text = null;
        let response_headers = original_response.headers;
        let new_response_headers = new Headers(response_headers);
        let status = original_response.status;
        
        if (disable_cache) {
            new_response_headers.set('Cache-Control', 'no-store');
        }
        new_response_headers.set('access-control-allow-origin', '*');
        new_response_headers.set('access-control-allow-credentials', true);
        new_response_headers.set('x-frame-options', 'ALLOW');
        new_response_headers.delete('content-security-policy');
        new_response_headers.delete('content-security-policy-report-only');
        new_response_headers.delete('clear-site-data');
        
        if (new_response_headers.get("x-pjax-url")) {
            new_response_headers.set("x-pjax-url", response_headers.get("x-pjax-url").replace("//" + upstream_domain, "//" + url_hostname));
        }
        
        const content_type = new_response_headers.get('content-type');
        if (content_type != null && content_type.includes('text/html') && content_type.includes('UTF-8')) {
            original_text = await replace_response_text(original_response_clone, upstream_domain, url_hostname);
        } else {
            original_text = original_response_clone.body
        }
        
        response = new Response(original_text, {
            status,
            headers: new_response_headers
        })
    }
    if (path == upstream_path) {
        return new Response(redirect, {headers: {'content-type': 'text/html;charset=UTF-8'}})
    }
    else {
        return response;
    }
}
async function replace_response_text(response, upstream_domain, host_name) {
    let text = await response.text()
    var i, j;
    for (i in replace_dict) {
        j = replace_dict[i]
        if (i == '$upstream') {
            i = upstream_domain
        } else if (i == '$custom_domain') {
            i = host_name
        }
        if (j == '$upstream') {
            j = upstream_domain
        } else if (j == '$custom_domain') {
            j = host_name
        }
        let re = new RegExp(i, 'g')
        text = text.replace(re, j);
    }
    return text;
}
async function device_status(user_agent_info) {
    var agents = ["Android", "iPhone", "SymbianOS", "Windows Phone", "iPad", "iPod"];
    var flag = true;
    for (var v = 0; v < agents.length; v++) {
        if (user_agent_info.indexOf(agents[v]) > 0) {
            flag = false;
            break;
        }
    }
    return flag;
}

解决过程

 1. 登录cloudflare,一定要有一个自己的域名在上面嗷~
 2. 去创建一个服务,准备反向代理,路径:cloudflare首页 --> Workers --> 创建服务

 3. 创建服务的名字随便写,只支持英文不支持中文,下面两个随便选一个都行,编辑好点击右下角蓝色按钮创建服务

 4. 创建好服后,我们会默认进入这个服务页面,然后点击右上角的快速编辑去修改

 5. 进入编辑界面把左侧的内容,换成我们通用反向代理代码里面的代码,然后修改三处位置,修改位置在代码说明和图片中已经写好了自己看吧

 6. 改好后我们点击下面的保存并部署,然后继续回到服务页面,点击左上角的哪个我们服务的名字就行

 7. 回到服后我们新建一个路由绑定一下站点,跟着图片操作即可

 8. 路由这里的名称我们写的时候建议使用二级域名吧,顶级域名一般用作它处,绑定的时候结尾一定要带 /*,区域选择一下绑定的域名,写好后我们点击添加路由即可

 9. 路由绑定好了,我们去域名的DNS解析一下,照着下面操作吧 应该看得懂什么意思,不懂的可以问,写好后我们就反向代理完了

举个反向代理使用的例子:

这样就知道怎么用了吧~

uptimerobot 监控

 uptimerobot监控是单独修改的,代码在前提条件这里自己复制吧,主要修改两个位置,反向代理方式和上面通用常规的一样

  • 第4行:const upstream_path = '/7w9kmszqLQ',这个 7w9kmszqLQ改成你自己uptimerobot监控预览界面的那一串
  • 第22行:改url=里面的内容改成你自己使用cloudflare反向代理后的链接,别问你咋知道你的链接是啥,你到时候在域名DNS解析的时候添加这个就是了
打 赏
  • 支付宝
  • 微信
  • QQ
Alipay
WeChatPay
QQPay
评论区
叶小明的博客 2023年04月08日 17:22
回复

能说看不懂吗

An_wen
1 条回复
An_wen
An_wen 2023年04月08日 17:23
回复

不行,没准你也需要~等你回来考古

avatar