镜像反代任何网站Workers-Proxy

低调G
2020-06-18 / 2 评论 / 4,172 阅读 / 正在检测是否收录...

介绍

Workers-Proxy 是基于 Cloudflare Workers 的轻量级 Javascript 反向代理.
用户无需购买主机并配置 Web 服务器 (例如 Nginx 或 Apache) 即可在 Cloudflare 的全球网络上部署反向代理.

功能

搭建网站镜像
通过 Cloudflare 的全球网络加速前端资源访问
增加安全性, 隐藏网站的真实 IP 地址
屏蔽特定地区或 IP 地址
将移动设备用户转发到不同网站

配置教程

安装和部署

使用 Wrangler 部署

1.安装 Wrangler.
2.创建一个新的项目.

wrangler generate my-workers-proxy https://github.com/Berkeley-Reject/Workers-Proxy

3.配置该项目的 wrangler.toml 文件来准备部署你的项目.

wrangler config

4.构建并部署于 Cloudflare Workers.

wrangler build
wrangler publish

手动部署

1.转到 Cloudflare Workers, 注册或登录 Cloudflare 账号, 为 Workers 设置子域名, 创建新的 Worker.
2.自定义 'src/index.js', 将代码复制到在线编辑器中, 替换默认代码.
3.更改 Worker 名称, 保存代码并部署, 测试反向代理是否符合需求.

绑定自定义域名

1.检查域名是否接入 Cloudflare.
2.跳转到域名的控制面板, 选择 'Workers' 页面, 点击 'Add Route'.
3.在 Route 中输入 https://<自定义域名>/* 并且选择刚创建的 Worker.
4.为自定义域名添加 CNAME DNS 记录. 在 DNS 页面中, 在 'Name' 区域输入自定义域名的子域名 (或者 @), 在 'Target' 区域输入 Worker 的二级域名 (例如 test.workers.dev), 将代理状态选择为 '代理'.

自定义 index.js

在 'index.js' 文件顶部有一些常量.
为了自定义 Workers-Proxy 反向代理, 请根据需求编辑这些常量.

// 代理网站
const upstream = 'www.google.com'

// 代理网站的目录
const upstream_path = '/'

// 手机用户代理网站
const upstream_mobile = 'www.google.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 = false

// 文本替换
const replace_dict = {
    '$upstream': '$custom_domain',
    '//google.com': ''
}

配置模板

Google
Google Scholars
GitHub
Wikipedia
Wikipedia (Chinese)
The New York Times
Pornhub

部署多个域名

如果被反代的网站使用其他域名的静态资源时, 可以部署多个 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': '<Workers-Proxy A 的域名>'
}

index.js代码

// 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;
}
0

评论 (2)

取消
  1. 头像
    低调哥 作者
    Android · UC Browser

    镜像了一个谷歌自用哈

    回复
  2. 头像
    资源窝
    Windows XP · Google Chrome

    站长有没有成功呢,没有看到演示站。

    回复