Cloudflare 新玩法利用 Workers 反向代理

前言

Cloudflare 推出了 Workers 服务,在国内一般叫它边缘计算。之前介绍的利用又拍云边缘规则为图片增加水印其实也是这个原理。

Workers-Proxy 是个 Github 开源项目,可以通过 Cloudflare Workers 服务搭建一个反向代理服务器,这个反向代理服务器不需要安装在我们自己的 VPS 主机上,而是直接部署在 Cloudflare 节点上,这可以极大的降低我们自身 VPS 主机的性能损耗。

步骤

  • 导航至 Cloudflare Workers ,注册并登录你的 Cloudflare 帐户,然后为 worker 设置自定义域名,然后创建一个新的 Worker 。
  • 访问打开 “ src / index.js ” ,将代码粘贴到 Cloudflare 刚刚新创建的 Worker ,然后在编辑器中以替换默认配置。
  • 更改 Worker 的名称,保存并部署它,最后检查其性能是否满足你的需求。
// 上游网站的域名
const upstream = 'github.com'

// 上游网站的路径
const upstream_path = '/'

// 上游网站的移动端域名
const upstream_mobile = 'github.com'

// 禁止访问的国家地区
const blocked_region = ['CN', 'KP', 'SY', 'PK', 'CU']

// 禁止使用服务的IP地址
const blocked_ip_address = ['0.0.0.0', '127.0.0.1']

// 是否开启上游网站的https
const https = true

// 是否关闭缓存
const disable_cache = true

// 替换文字
const replace_dict = {
    '$upstream': '$custom_domain'
}

如果网站使用另一个域名来提供静态资源,则用户可以部署多个Workers-Proxy并配置文本替换。

  • www.google.com 调用 www.gstatic.com 上的静态资源
  • 部署 Workers-Proxy A 反向代理 www.gstatic.com
  • 部署 Workers-Proxy B 反向代理 www.google.com
  • Workers-Proxy B 配置文本替换:
const replace_dict = {
    '$upstream': '$custom_domain',
    'www.gstatic.com': '<Domain name of Workers-Proxy A>'
}

防止大家打不开 Github 我在最后贴出 src / index.js 完整的源代码,你可以直接复制下面的代码部署 Workers 。

// Website you intended to retrieve for users.
const upstream = 'www.google.com'

// Custom pathname for the upstream website.
const upstream_path = '/'

// Website you intended to retrieve for users using mobile devices.
const upstream_mobile = 'www.google.com'

// Countries and regions where you wish to suspend your service.
const blocked_region = ['CN', 'KP', 'SY', 'PK', 'CU']

// IP addresses which you wish to block from using your service.
const blocked_ip_address = ['0.0.0.0', '127.0.0.1']

// 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',
    '//google.com': ''
}

addEventListener('fetch', event => {
    event.respondWith(fetchAndApply(event.request));
})

async function fetchAndApply(request) {
    const region = request.headers.get('cf-ipcountry').toUpperCase();
    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.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;
}

后语

写到这里聪明的小伙伴应该能知道这东西可以怎么玩了,我简单说一下我的玩法。

我在利用又拍云创建带水印的缩略图,利用又拍云提供的测试域名可以访问生成的带水印的图片,然后通过 Cloudflare Workers 创建反向代理并 CDN 缓存加速。然后网站前端调用 Cloudflare 加速后带水印的水印图片!

可以参考下面这篇文章利用又拍云边缘规则自动为图片添加水印:

Cloudflare 新玩法利用 Workers 反向代理 - 反向代理, Proxy, Cloudflare
Cloudflare 新玩法利用 Workers 反向代理 - 反向代理, Proxy, Cloudflare

WordPress 通过又拍云 CDN 边缘规则不改变链接并自动给图片添加水印

给TA买糖
共{{data.count}}人
人已赞赏
VPS教程

使用 CloudFlare CDN 以后 Nginx 无法获取访客真实 IP 的解决方法

2020-9-5 4:03:56

VPS教程

宝塔面板安装第三方 PHP 扩展 libsodium sodium

2020-10-19 13:34:06

0 条回复 A文章作者 M管理员
    暂无讨论,说说你的看法吧
个人中心
购物车
优惠劵
今日签到
有新私信 私信列表
搜索