Files
cf-favicon/README.md
2026-06-24 22:10:24 +08:00

3.1 KiB
Raw Blame History

Favicon 代理 APICloudflare Workers

通过 HTTP API 代理获取任意网站的 favicon解决国内无法直连部分站点的问题。
使用 GoogleDuckDuckGo直连目标站 /favicon.ico首页 HTML 中的 <link rel="icon"> 多路同时请求,谁先成功返回就用谁

前端为 React + Vite 静态站点,由 Workers Static Assets 托管;/api/favicon 在同一 Worker 上运行,Worker 脚本仅包含 API 逻辑React 产物在资源目录中,不计入 Worker bundle

说明Bing 没有公开的 favicon 接口,因此第二源使用 DuckDuckGo。

接口说明

  • 方法: GET
  • 路径: /api/favicon
  • 参数:
    • url / domain / u(必填):目标网站完整 URL 或域名,如 https://twitter.comgithub.com
    • size(可选):图标尺寸 16256默认 128仅对 Google 源生效)

示例

curl -o favicon.ico "https://你的Workers域名/api/favicon?url=https://twitter.com"
curl -o favicon.ico "https://你的Workers域名/api/favicon?domain=github.com&size=64"

前端使用:

<img src="https://你的Workers域名/api/favicon?url=https://example.com" alt="favicon" width="32" height="32" />

开发与构建

npm install
npm run dev          # Vite + Workers 本地开发(同官方 Cloudflare Vite 插件)
npm run build        # tsc -b && vite build → dist/client + dist/cf_favicon
npm run deploy       # 构建后 wrangler deploy等价于下面单独一条命令的效果

部署到 Cloudflare Workers

  1. 安装 Wrangler 并登录:wrangler login
  2. 在项目根目录执行:
wrangler deploy

Wrangler 会根据 wrangler.toml 中的 [build] command 先执行 npm run build,再上传 Worker约几 KiB与静态资源目录 dist/client。自定义域名可在 Dashboard 中为该 Worker 绑定。

项目结构(概要)

├── src/
│   ├── App.tsx          # 说明页React
│   ├── worker/
│   │   ├── index.ts    # Worker 入口(仅路由 /api/favicon
│   │   └── favicon.ts  # Favicon 代理实现
├── index.html           # Vite 入口
├── vite.config.ts       # @cloudflare/vite-plugin + React
├── wrangler.toml        # Workers + Static AssetsSPA 回退)
└── public/              # 可选:根路径 /favicon.icoAPI 全源失败时的回退图标

行为说明

  • 多路竞速详见上文;成功时返回图片及 Cache-Control: public, max-age=86400
  • 回退:若全部外部源失败,会通过 env.ASSETS 读取站点静态资源中的 /favicon.ico(请将可选图标放在 public/favicon.ico,构建后为站点根路径)。存在则返回 200 并带 X-Favicon-Fallback: true,否则 502 JSON。
  • 运行在 Cloudflare 边缘,出站请求由 CF 发起,相当于代理访问。

License

MIT