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

Next.js嵌套动态路由页面刷新出现404错误求助

解决Next.js嵌套动态路由刷新后返回404的问题

问题描述

使用Next.js嵌套动态路由时,刷新页面后出现404 Not Found错误。页面结构如下:

pages
  [storeName]
     summaries.jsx
     [store-insight].jsx

访问类似 www.url.com/storeName/10 的路径时,需提取URL中的10作为API请求参数。本地localhost环境刷新正常,仅生产环境出现问题。

问题原因

Next.js开发环境自带的服务器会自动处理动态路由匹配,但生产环境中如果使用静态托管平台(非Vercel)或自定义服务器,服务器无法识别动态路由规则,直接返回404。

解决方案

方案1:配置服务器路由重写(自定义服务器/非Vercel托管)

需要让服务器将所有请求转发到index.html,由Next.js客户端路由处理:

Nginx配置示例:

location / {
  try_files $uri $uri/ /index.html;
}

Apache配置示例(.htaccess):

RewriteEngine On
RewriteBase /
RewriteRule ^index\.html$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.html [L]

方案2:静态生成(getStaticPaths + getStaticProps)

如果路由参数可预先生成,用静态生成预渲染所有可能的页面:

// 在[store-insight].jsx中添加
export async function getStaticPaths() {
  // 从API获取所有店铺ID和名称
  const res = await fetch('你的店铺列表API地址');
  const stores = await res.json();

  const paths = stores.map(store => ({
    params: { 
      storeName: store.name, 
      'store-insight': store.id.toString() 
    }
  }));

  return { paths, fallback: 'blocking' }; // blocking模式自动渲染未预生成的路径
}

export async function getStaticProps({ params }) {
  const { storeName, 'store-insight': storeId } = params;
  const res = await fetch(`你的店铺数据API地址?storeId=${storeId}`);
  const storeData = await res.json();

  return {
    props: { storeData, storeName, storeId },
    revalidate: 60 // 可选:每60秒重新验证数据
  };
}

方案3:服务器端渲染(getServerSideProps)

如果需要实时数据,用服务器端渲染处理每次请求:

// 在[store-insight].jsx中添加
export async function getServerSideProps({ params }) {
  const { storeName, 'store-insight': storeId } = params;
  const res = await fetch(`你的店铺数据API地址?storeId=${storeId}`);
  const storeData = await res.json();

  return {
    props: { storeData, storeName, storeId }
  };
}

方案4:Vercel托管配置检查

如果部署在Vercel上,默认支持动态路由,但需确认:

  • next.config.js无禁用动态路由的配置
  • Vercel部署设置中启用了自动路由检测

额外优化建议

  1. 规范参数传递方式:当前通过split('&')解析多参数的方式不够规范,建议改用查询参数(如/storeName/insight?id=10&name=xxx)或拆分动态路由段。
  2. 封装参数解析逻辑:页面和组件中重复的storeDetails函数可封装为自定义Hook,减少冗余代码。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.24 07:05:44