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

如何在Firebase Hosting中仅为目录强制添加尾部斜杠

解决Firebase Hosting仅为目录强制添加尾部斜杠的方案

要实现仅针对目录(对应index.html的路径)执行301重定向添加尾部斜杠,同时保留页面路径(对应xxx.html)无斜杠的200响应,可通过以下firebase.json配置实现:

{
  "hosting": {
    "cleanUrls": true,
    "trailingSlash": false,
    "redirects": [
      {
        "source": "!/(*.*)",
        "condition": {
          "exists": "/$1/index.html"
        },
        "destination": "/$1/",
        "type": 301
      }
    ]
  }
}

配置说明

  • trailingSlash: false:关闭全局尾部斜杠强制规则,避免页面路径被错误重定向。
  • cleanUrls: true:保留自动移除.html扩展名的功能,确保/foo/bar/page能正常对应/foo/bar/page.html并返回200状态码。
  • 重定向规则细节:
    • source: "!/(*.*)":匹配所有不含小数点的请求路径(排除图片、CSS等带扩展名的资源请求)。
    • condition: { "exists": "/$1/index.html" }:仅当请求路径对应的目录下存在index.html时(即该路径是一个目录),才触发重定向。
    • destination: "/$1/":将请求重定向到带尾部斜杠的路径。
    • type: 301:使用永久重定向,符合SEO最佳实践。

效果验证

  • 请求/foo/bar/page:匹配/foo/bar/page.html,返回200状态码。
  • 请求/foo/bar/:匹配/foo/bar/index.html,返回200状态码。
  • 请求/foo/bar:检测到/foo/bar/index.html存在,执行301重定向到/foo/bar/。

若目录下无index.html文件,请求不带斜杠的路径会返回404,这符合你接受的备选方案。

内容的提问来源于stack exchange,提问作者Peque

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.27 09:43:16