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

Next.js使用Meta Refresh/redirect跳转/login遇404问题求助

Next.js开发模式下/login页面404问题解决方法

问题背景

尝试通过首页重定向到/login页面,但直接访问/login时返回404,相关代码如下:

首页重定向代码(index.tsx)

第一种尝试(meta标签刷新):

import Head from "next/head";

const Home = () => {
  return (
    <Head>
      <meta httpEquiv="refresh" content="0; url=/login" />
    </Head>
  );
}
export default Home;

第二种尝试(Next.js redirect函数):

import { redirect } from 'next/navigation';

const Home = () => redirect('/login/');
export default Home;

登录页代码(pages/login/login.tsx)

import Head from "next/head";
import styles from "@/styles/Home.module.css";

export default function Home() {
  return (
    <>
      <Head>
        <title>Hello world</title>
      </Head>
      <main className={styles.main}>
        <h1>Hello world</h1>
      </main>
    </>
  );
}

问题原因与解决方案

  • 路由映射错误:Next.js Pages Router的路由规则基于pages目录的文件结构生成,pages/login/login.tsx对应的路由是/login/login,而非你期望的/login。
  • 修正文件结构:将pages/login/login.tsx移动到pages/login.tsx,此时该文件对应的路由就是/login,访问即可正常加载页面。
  • 重定向代码优化:使用redirect函数时,保持路径与目标路由一致,比如目标是/login,则写redirect('/login')(避免末尾多余的斜杠,减少路径匹配歧义)。
  • 关于historyApiFallback:Next.js开发服务器默认已内置SPA路由的 fallback 处理逻辑,无需在next.config.js中额外配置类似webpack的historyApiFallback,你的问题核心并非fallback配置问题。

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

相关产品推荐
方舟 Agent Plan

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

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