Cloudflare Worker 反向代理方案加速 Docker Hub、HuggingFace、GitHub 等站点

1. 创建 Worker

在 Cloudflare Dashboard → Workers & Pages → Create Worker,贴入以下代码:

const PROXY_RULES = {
  'docker.yourdomain.com': 'registry-1.docker.io',
  'ghcr.yourdomain.com': 'ghcr.io',
  'github.yourdomain.com': 'github.com',
  'raw.yourdomain.com': 'raw.githubusercontent.com',
  'hf.yourdomain.com': 'huggingface.co',
  'ghrel.yourdomain.com': 'objects.githubusercontent.com',
};

export default {
  async fetch(request) {
    const url = new URL(request.url);
    const upstream = PROXY_RULES[url.hostname];

    if (!upstream) {
      return new Response('Not configured', { status: 404 });
    }

    url.hostname = upstream;

    const newRequest = new Request(url, {
      method: request.method,
      headers: request.headers,
      body: request.body,
      redirect: 'follow',
    });

    newRequest.headers.set('Host', upstream);

    const response = await fetch(newRequest);

    const newHeaders = new Headers(response.headers);
    // 处理 Docker Registry 的认证重定向
    const wwwAuth = newHeaders.get('www-authenticate');
    if (wwwAuth) {
      newHeaders.set(
        'www-authenticate',
        wwwAuth.replace(
          'https://auth.docker.io',
          `https://${request.headers.get('host')}`
        )
      );
    }

    return new Response(response.body, {
      status: response.status,
      headers: newHeaders,
    });
  },
};

2. 绑定自定义域名

在 Worker 设置 → Triggers → Custom Domains,添加:

子域名 用途
docker.yourdomain.com Docker Hub
ghcr.yourdomain.com GitHub Container Registry
github.yourdomain.com GitHub
raw.yourdomain.com GitHub Raw 文件
hf.yourdomain.com HuggingFace
ghrel.yourdomain.com GitHub Releases 下载

前提:域名已托管在 Cloudflare DNS 上。

3. 使用方式

Docker

# /etc/docker/daemon.json
{
  "registry-mirrors": ["https://docker.yourdomain.com"]
}

# 重启 docker
sudo systemctl restart docker

# 拉取镜像
docker pull docker.yourdomain.com/library/nginx:latest

HuggingFace

export HF_ENDPOINT=https://hf.yourdomain.com
pip install -U huggingface_hub
huggingface-cli download meta-llama/Llama-2-7b

GitHub Release / Raw 文件

# 下载 release
wget https://ghrel.yourdomain.com/user/repo/releases/download/v1.0/file.tar.gz

# raw 文件
curl https://raw.yourdomain.com/user/repo/main/README.md


### Git Clone(通过代理)

bash
git clone https://github.yourdomain.com/user/repo.git

4. 注意事项