Firebase Cloud Function对favicon.ico/robots.txt路径不执行问题
Firebase Hosting重写favicon.ico/robots.txt到SSR函数却直接返回404的问题
我配置了Firebase Hosting与Cloud Function,在firebase.json里通过重写规则把所有路径指向SSR函数,仅sitemap_index.xml指向serveSitemap函数。SSR函数基于Express构建,本地模拟器和部署环境中,访问sitemap.xml等路径时函数正常执行,但访问favicon.ico和robots.txt时,请求虽被正确重写到SSR函数,却没执行函数直接返回404,求原因。
相关配置代码
firebase.json配置
{ "functions": { "predeploy": [ "yarn --cwd \"$RESOURCE_DIR\" lint", "yarn --cwd \"$RESOURCE_DIR\" build" ], "source": "functions" }, "hosting": [ { "target": "dev", "public": "public", "ignore": ["firebase.json", "**/.*", "**/node_modules/**"], "rewrites": [ { "source": "/sitemap_index.xml", "function": "serveSitemap", "region": "europe-west1" }, { "source": "**", "function": "ssr", "region": "europe-west1" } ] } ] }
SSR函数代码
const universalApp = require(`${process.cwd()}/dist/server/main.js`).app; const app = universalApp(); // Express实例 export const ssr = functions.region(FUNCTIONS_REGION).https.onRequest(app);
模拟器日志示例
访问sitemap.xml时的日志
[hosting] Rewriting /sitemap.xml to http://127.0.0.1:5001/intergun-dev/europe-west1/ssr for local Function europe-west1/ssr i functions: Beginning execution of "ssr" i functions: Finished "ssr" in 17.807421ms i hosting: 127.0.0.1 - - [30/Dec/2022:22:35:05 +0000] "GET /sitemap.xml HTTP/1.1" 200 339 "-" "Mozilla/5.0 (Macintosh; Intel Mac OS X 10.15; rv:108.0) Gecko/20100101 Firefox/108.0"
访问favicon.ico时的日志
[hosting] Rewriting /favicon.ico to http://127.0.0.1:5001/intergun-dev/europe-west1/ssr for local Function europe-west1/ssr i hosting: 127.0.0.1 - - [30/Dec/2022:22:38:35 +0000] "GET /favicon.ico HTTP/1.1" 404 0 "-" "Mozilla/5.0 (Macintosh; Intel Mac OS X 10.15; rv:108.0) Gecko/20100101 Firefox/108.0"
问题原因及解决方法
这是Firebase Hosting的默认文件优先级规则导致的:Firebase Hosting会优先检查public目录下是否存在请求的特殊文件(比如favicon.ico、robots.txt),即使目录里没有这些文件,Hosting内部机制也会直接返回404,跳过重写规则触发Cloud Function的步骤。
解决方法有两种:
- 显式添加重写规则:在
rewrites数组最顶部添加针对favicon.ico和robots.txt的规则,覆盖默认行为:
"rewrites": [ { "source": "/sitemap_index.xml", "function": "serveSitemap", "region": "europe-west1" }, { "source": "/favicon.ico", "function": "ssr", "region": "europe-west1" }, { "source": "/robots.txt", "function": "ssr", "region": "europe-west1" }, { "source": "**", "function": "ssr", "region": "europe-west1" } ]
- 禁用静态文件托管:如果不需要Hosting托管任何静态文件,将
public字段设为空字符串"",这样Hosting会直接跳过静态文件检查,所有请求都走重写规则。但注意如果public目录下有其他需托管的资源,这种方法不适用。
内容的提问来源于stack exchange,提问作者Jesper
相关产品推荐
相关产品推荐

