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

NextJS项目发布后Dynamic Routes动态路由失效问题求助

问题分析与解决办法

核心问题

你用相对路径./public/assets/data/pages/读取目录导致的问题。开发环境下项目根目录就是工作目录,路径能正常解析;但部署构建时,工作目录可能发生变化,fs.readdirSync找不到目标目录,动态生成的路由条目根本没被加到exportPathMap里,所以部署后这些路由失效。

解决步骤

1. 替换为绝对路径

用path.join(__dirname, 'public/assets/data/pages')构建绝对路径,确保无论在哪运行都能正确找到目录。修改后的完整代码如下:

const fs = require("fs");
const path = require("path");
/** @type {import('next').NextConfig} */
const nextConfig = {
  reactStrictMode: true,
  swcMinify: true,
  distDir: "build",
  trailingSlash: true,
  sassOptions: {
    includePaths: [path.join(__dirname, "styles")],
  },
  exportPathMap: async function (
    defaultPathMap,
    { dev, dir, outDir, distDir, buildId }
  ) {
    // 构建绝对路径,避免环境差异导致的路径错误
    const pagesDir = path.join(__dirname, "public/assets/data/pages");
    let dynamicRoutes = {};
    
    // 增加异常捕获,防止目录不存在导致构建失败
    try {
      dynamicRoutes = Object.fromEntries(
        fs.readdirSync(pagesDir).map(i => [`/ac/${i}`, { page: '/ac/[id]' } ])
      );
    } catch (err) {
      console.error("读取pages目录失败:", err);
    }

    return {
      "/": { page: "/" },
      "/ac/asrar_archived": { page: "/ac/[id]" },
      "/ac/eqbal": { page: "/ac/[id]" },
      "/ac/fum": { page: "/ac/[id]" },
      "/ac/hakimtoos": { page: "/ac/[id]" },
      ...dynamicRoutes
    };
  },
};

module.exports = nextConfig;

2. 验证构建结果

执行next build && next export后,检查out/ac/目录下是否生成了对应动态路由的文件夹(比如out/ac/asrar_archived/、out/ac/eqbal/等),如果存在说明路由生成成功。

3. 服务器配置(非Vercel环境)

如果部署在Nginx、Apache等第三方服务器,需要配置路由 fallback 到index.html,否则刷新动态路由会出现404:

  • Nginx示例:在站点配置的location /块里添加try_files $uri $uri/ /index.html;
  • Apache示例:启用mod_rewrite模块后,在.htaccess里添加规则RewriteRule ^ index.html [L]

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.24 13:23:32