Firebase Hosting重写规则代理外部API返回404,如何解决?
Firebase Hosting重写外部API返回404的解决方案
是的,Firebase Hosting的重写规则不支持直接指向外部域名,这就是你配置后API路由返回404的核心原因。Firebase Hosting的destination字段仅支持指向托管的静态文件、内部Cloud Functions/Cloud Run服务,无法直接转发请求到外部域名。
下面提供两种可行的解决办法:
方法一:用Cloud Functions做中间代理
通过Cloud Functions创建一个代理函数,将/api/**路径的请求转发到原API地址:
安装依赖并初始化Functions(如果未初始化过)
npm install firebase-functions firebase-admin axios firebase init functions在
functions/index.js中编写代理逻辑const functions = require("firebase-functions"); const axios = require("axios"); exports.proxyApi = functions.https.onRequest(async (req, res) => { try { // 提取/api后的路径,拼接原API地址 const apiPath = req.path.replace(/^\/api/, ""); const targetUrl = `https://example.com/api${apiPath}`; // 完整转发请求的方法、头信息、请求体 const response = await axios({ method: req.method, url: targetUrl, headers: { ...req.headers, host: "example.com" }, // 修正Host头适配原API验证 data: req.body, responseType: "stream" }); // 转发响应头和响应内容到客户端 res.set(response.headers); response.data.pipe(res); } catch (err) { res.status(err.response?.status || 500).send(err.message); } });修改
firebase.json的重写规则,指向代理函数{ "hosting": { "public": "dist", "ignore": ["firebase.json", "**/.*", "**/node_modules/**"], "rewrites": [ { "source": "/api/**", "function": "proxyApi" }, { "source": "**", "destination": "/index.html" } ] } }部署函数和托管站点
firebase deploy --only functions,hosting
方法二:直接让前端请求原API(需配置CORS)
如果原API支持跨域请求(CORS),可以直接修改前端代码中的API基础地址为https://example.com/api,同时确保原API服务器配置了CORS规则,允许你的Firebase Hosting域名(如your-project-id.web.app或自定义域名)发起跨域请求。
注意事项
- 使用Cloud Functions代理时,需关注函数的配额限制和计费规则,高流量场景需评估成本;
- 代理复杂请求(如文件上传)时,可能需要调整请求转发的配置,确保数据完整传递;
- 若原API有基于Host头的访问验证,必须在代理时修正Host头为原API的域名,否则可能被拦截。
内容的提问来源于stack exchange,提问作者vdegenne
相关产品推荐
相关产品推荐

