You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何修改Firebase Cloud Function的URL以适配Cloudflare子域名?

解决方案

方案1:Cloudflare Workers 反向代理(推荐,支持隐藏原始URL)

这是最灵活的实现方式,全程在Cloudflare侧完成请求转发,无需改动Firebase原有配置:

  1. 登录Cloudflare控制台,创建新的Worker
  2. 替换Worker代码为以下内容(按需修改占位符):
export default {
  async fetch(request) {
    const url = new URL(request.url);
    const functionName = url.pathname.slice(1);
    // 替换为你的Firebase Cloud Functions基础地址
    const targetUrl = `https://<region>-<project-id>.cloudfunctions.net/${functionName}`;

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

    return fetch(proxyRequest);
  }
};
  1. 在Cloudflare「路由」配置中,将https://<cloudflare-subdomain>.<website-domain>/*绑定到该Worker
  2. 测试访问目标URL,确认请求正常转发到Firebase函数

方案2:Cloudflare Page Rules URL转发(适合简单场景)

如果不需要隐藏Firebase函数的原始URL,可直接用Page Rules做动态重定向:

  • 进入Cloudflare控制台「Page Rules」,新建规则
  • 匹配URL设为https://<cloudflare-subdomain>.<website-domain>/*
  • 动作选择「转发URL」,类型设为「动态」,目标URL填写https://<region>-<project-id>.cloudfunctions.net/$1($1会自动匹配路径中的函数名称)
  • 选择转发类型(临时302或永久301)后保存

方案3:绑定Cloudflare子域名到Firebase Hosting + 重写规则

若你的Firebase Hosting已通过Cloudflare管理域名,可将目标子域名绑定到Hosting后用重写规则转发:

  1. 在Firebase控制台Hosting板块,添加https://<cloudflare-subdomain>.<website-domain>作为自定义域名,按照指引在Cloudflare配置CNAME记录完成DNS验证
  2. 修改项目根目录的firebase.json,添加重写规则:
{
  "hosting": {
    "public": "public",
    "rewrites": [
      {
        "source": "/:functionName",
        "function": ":functionName"
      }
    ]
  }
}
  1. 重新部署Firebase Hosting,此时访问目标子域名下的函数路径即可转发到对应Cloud Function

内容的提问来源于stack exchange,提问作者slhn.dev

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.15 16:06:00