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

Next.js能否将多级静态路由重写为短URL?

在Next.js中通过Rewrites实现短URL访问静态生成页面

要实现将/[category]/[subCategory]/[slug]格式的静态页面,通过/[slug]的短URL访问,核心是利用Next.js的rewrites配置完成请求路径的内部映射,以下分两种路由方案说明实现方式:

一、Pages Router(Next.js 12及更早版本)

在项目根目录的next.config.js中配置重写规则,需要提前获取所有文章的slug与对应category、subCategory的映射关系(可从本地数据文件或CMS中获取):

  1. 准备文章映射数据
    比如创建posts.js文件存储所有静态页面的路径信息:

    // posts.js
    export const posts = [
      { slug: 'bananaPost', category: 'fruit', subCategory: 'banana' },
      // 其他静态页面的映射数据...
    ];
    
  2. 配置next.config.js

    const { posts } = require('./posts');
    
    /** @type {import('next').NextConfig} */
    const nextConfig = {
      async rewrites() {
        // 为每个slug生成独立的重写规则
        const slugRewriteRules = posts.map(post => ({
          source: `/${post.slug}`,
          destination: `/${post.category}/${post.subCategory}/${post.slug}`
        }));
    
        return {
          beforeFiles: slugRewriteRules, // 优先匹配这些重写规则
        };
      },
      // 其他项目配置...
    };
    
    module.exports = nextConfig;
    

二、App Router(Next.js 13+)

App Router的rewrites配置逻辑与Pages Router一致,同样在next.config.js中完成,页面结构对应app/[category]/[subCategory]/[slug]/page.js:

const { posts } = require('./posts');

/** @type {import('next').NextConfig} */
const nextConfig = {
  async rewrites() {
    const slugRewriteRules = posts.map(post => ({
      source: `/${post.slug}`,
      destination: `/${post.category}/${post.subCategory}/${post.slug}`
    }));

    return {
      beforeFiles: slugRewriteRules,
    };
  },
  // 其他项目配置...
};

module.exports = nextConfig;

关键注意事项

  • 全局唯一slug:必须确保所有静态页面的slug是全局唯一的,否则重写规则会冲突,仅会匹配到第一个符合条件的规则。
  • 静态生成适配:重写规则需要在build阶段确定,因此映射数据必须提前准备好(如果用CMS,可在build脚本中先拉取数据再生成规则)。
  • 测试方式:需执行npm run build && npm start启动生产环境服务器测试,开发环境下可能需要刷新页面才能生效规则。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.14 09:21:15