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

Next.js动态路由在Firebase Hosting刷新404问题求助

解决Next.js静态导出部署Firebase Hosting动态路由刷新404问题

核心问题在于:静态导出的Next.js动态路由,Firebase Hosting无法直接匹配/job/xxx这类路径到对应的静态文件,需要通过顺序正确的rewrite规则将请求映射到实际生成的静态文件上——具体路由规则必须放在兜底规则前面。

第一步:确认Next.js路由类型与导出结构

先检查你的out目录结构,对应两种路由方案:

  • App Router(app/job/[jobId]/page.js):导出后会生成out/job/[jobId]/index.html
  • Pages Router(pages/job/[jobId].js):默认导出后生成out/job/[jobId].html;若开启trailingSlash: true,则生成out/job/[jobId]/index.html

第二步:修改firebase.json的rewrites规则

根据你的路由类型替换对应的hosting配置:

方案1:适配App Router(或开启trailingSlash的Pages Router)

{
  "hosting": {
    "public": "out",
    "ignore": [
      "firebase.json",
      "**/.*",
      "**/node_modules/**"
    ],
    "cleanUrls": true,
    "rewrites": [
      // 先匹配/job/xxx这类动态路由,映射到实际静态文件
      {
        "source": "/job/*",
        "destination": "/job/[jobId]/index.html"
      },
      // 兜底规则:所有其他请求转到首页,保证客户端路由正常
      {
        "source": "**",
        "destination": "/index.html"
      }
    ]
  },
  "functions": [
    {
      "source": "functions",
      "codebase": "default",
      "ignore": [
        "node_modules",
        ".git",
        "firebase-debug.log",
        "firebase-debug.*.log"
      ],
      "predeploy": ["npm --prefix \"$RESOURCE_DIR\" run build"]
    }
  ]
}

方案2:适配未开启trailingSlash的Pages Router

{
  "hosting": {
    "public": "out",
    "ignore": [
      "firebase.json",
      "**/.*",
      "**/node_modules/**"
    ],
    "cleanUrls": true,
    "rewrites": [
      {
        "source": "/job/*",
        "destination": "/job/[jobId].html"
      },
      {
        "source": "**",
        "destination": "/index.html"
      }
    ]
  },
  "functions": [
    {
      "source": "functions",
      "codebase": "default",
      "ignore": [
        "node_modules",
        ".git",
        "firebase-debug.log",
        "firebase-debug.*.log"
      ],
      "predeploy": ["npm --prefix \"$RESOURCE_DIR\" run build"]
    }
  ]
}

第三步:关键注意事项

  1. 不要在destination中加out/:因为public已经指定为out,Firebase会自动从out目录查找文件,加了反而会导致路径错误。
  2. 确保next.config.js配置正确:必须添加output: 'export'才能生成静态导出的目录结构,示例:
/** @type {import('next').NextConfig} */
const nextConfig = {
  output: 'export',
  // 若需要开启trailingSlash,添加此行:
  // trailingSlash: true,
};

module.exports = nextConfig;
  1. 重新构建并部署:执行next build && next export生成最新的out目录,再运行firebase deploy生效配置。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.06 02:35:15