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

Next.js重写路由后,如何跳转至对应源路径而非目标路径?

解决方案

要实现点击按钮跳转至当前页面对应的rewrites源路径前缀,核心是从用户实际访问的URL中提取第一个路径段,判断是否属于配置的rewrite前缀列表,再进行跳转。

方法一:使用原生浏览器API

直接通过window.location获取当前URL,处理路径后跳转:

<button
    onClick={() => {
        // 定义rewrites配置中的前缀列表
        const rewritePrefixes = ['one', 'two', 'three', 'four'];
        const path = window.location.pathname;
        // 分割路径并过滤空字符串(处理开头的/)
        const pathSegments = path.split('/').filter(seg => seg);
        const firstSegment = pathSegments[0];

        // 判断前缀是否在列表中,跳转对应路径
        if (firstSegment && rewritePrefixes.includes(firstSegment)) {
            window.location.href = `/${firstSegment}`;
        } else {
            window.location.href = '/';
        }
    }}
>
    Redirect
</button>

方法二:使用Next.js的useRouter钩子(推荐)

Next.js提供的useRouter可以更优雅地获取当前显示的URL(即用户访问的源路径,而非rewrite后的目标路径):

import { useRouter } from 'next/router';

// 在组件内部
const router = useRouter();

<button
    onClick={() => {
        const rewritePrefixes = ['one', 'two', 'three', 'four'];
        const pathSegments = router.asPath.split('/').filter(seg => seg);
        const firstSegment = pathSegments[0];

        if (firstSegment && rewritePrefixes.includes(firstSegment)) {
            router.push(`/${firstSegment}`);
        } else {
            router.push('/');
        }
    }}
>
    Redirect
</button>

原理说明

Next.js的rewrites是服务器端的路径映射,客户端浏览器地址栏显示的仍然是用户实际访问的源路径(比如/four/0218309120/content)。我们只需要提取该路径的第一个有效段(four),判断是否属于配置的rewrite前缀,即可跳转至对应的源路径根目录(/four)。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.31 11:45:23