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

如何在Next.js单个路由中去除路径末尾的斜杠

Next.js 特定页面移除路由末尾斜杠解决方案

Next.js 内置的 trailingSlash 配置为全局生效,无法直接对部分页面生效,可通过以下方案实现针对性配置:

1. 调整页面目录结构(Pages Router 优先推荐)

如果使用Pages Router,路由末尾自动加斜杠通常是页面目录结构导致的:

  • 若你创建的是 pages/test/index.js 路由,默认会匹配 /test/ 路径
  • 直接创建 pages/test.js(而非test文件夹+index.js),默认匹配的路径就是 /test,不会自动加末尾斜杠

2. 配置next.config.js重定向规则

无需修改业务代码,通过重定向规则仅对指定路径移除末尾斜杠:

// next.config.js
module.exports = {
  async redirects() {
    return [
      {
        // 匹配需要移除末尾斜杠的路径,支持正则匹配多个路径
        source: '/(test|example|custom-page)/',
        // 重定向到不带斜杠的路径,查询参数会自动保留
        destination: '/$1',
        permanent: true, // 用301永久重定向,临时重定向可设为false
      },
      // 有动态参数的路径可以单独配置
      {
        source: '/post/:slug/',
        destination: '/post/:slug',
        permanent: true,
      }
    ]
  }
}

3. 用中间件实现更灵活的自定义规则

如果规则比较复杂(比如需要判断动态路径的特定场景),可以通过Next.js中间件处理:

// middleware.ts
import { NextResponse } from 'next/server'
import type { NextRequest } from 'next/server'

export function middleware(request: NextRequest) {
  const { pathname, search } = request.nextUrl
  // 仅对指定路径做末尾斜杠移除处理
  const targetPaths = ['/test', '/post']
  const isTargetPath = targetPaths.some(path => pathname.startsWith(path))
  
  if (isTargetPath && pathname.endsWith('/')) {
    // 移除末尾斜杠,保留查询参数
    const newPath = pathname.slice(0, -1) + search
    return NextResponse.redirect(new URL(newPath, request.url), {
      status: 301
    })
  }
  return NextResponse.next()
}

// 配置中间件生效的路径范围
export const config = {
  matcher: ['/test/:path*', '/post/:path*'],
}

注意:如果已经开启了全局 trailingSlash: true,需要先关闭该配置,再通过上述方案给需要加斜杠的页面单独配置重定向即可。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.28 11:03:00