Next.js 从 v9 起就原生支持把 pages/、app/、components/ 等目录放在 src/ 下,为了更清晰地分离“源代码”和其他项目文件(如配置文件、README 等)。
| 目录结构 | 是否默认支持 | 默认路由行为 |
|---|---|---|
pages/index.js |
是 | / 路由 |
src/pages/index.js |
是 | / 路由 |
app/page.tsx |
是 (App Router) | / 路由 |
src/app/page.tsx |
是 (App Router) | / 路由 |
指定访问 / 时展示其他页面内容的方式:
src/pages/index.js 中重定向例如你想默认跳转到 /home:
// src/pages/index.js
import { useEffect } from 'react'
import { useRouter } from 'next/router'
export default function Index() {
const router = useRouter()
useEffect(() => {
router.replace('/home') // 无历史记录跳转
}, [])
return null // 或 loading 占位符
}
如果你用的是 pages/ 目录,这是最推荐的方式。
redirects 配置(服务端 301/302 重定向)在 next.config.js 中添加:
// next.config.js
module.exports = {
async redirects() {
return [
{
source: '/',
destination: '/home', // 你想跳转的默认页面
permanent: false, // true 为 301,false 为 302
},
]
},
}
然后重启服务。
/home 这个路径。index.js 里如果只是内容复用,比如你有一个 HomePage 页面组件,想用它作为首页,可以直接 import:
// src/pages/index.js
import HomePage from './home'
export default function Index() {
return <HomePage />
}
/ 所映射的文件路径Next.js 不支持通过配置文件更改“访问 / 加载哪个文件”,它始终会找 pages/index.js(或 app/page.tsx)作为 / 的实际入口。这是框架默认约定,不能直接更改。
| 方式 | 特点 | 是否推荐 |
|---|---|---|
router.replace('/home') |
客户端跳转,快速灵活 | 推荐 |
next.config.js → redirects |
服务端重定向,适合 SEO | 推荐 |
| 直接 import 页面内容 | 简单复用,不跳路径 | 推荐 |
修改默认 / 映射路径 |
不支持 | 不推荐 |