在NextJS中重定向通配符路由



在部署新的NextJS应用程序时,需要从旧的非NextJS站点中保留一些遗留路由。

/const-string-[long-unique-hash]目前用于httpd配置重定向:

交货。RewriteRule ^const-string-(.*)$ https://google.com?q=const-string-$1 [L,NC]

如何保留NextJS路由,但允许遗留路由匹配路径:/const-string-*?

所需行为:

  1. /blogroutespages/blog.js

  2. /const-string-a1b2c3d4https://google.com?q=const-string-a1b2c3d4的路由

当前行为(目前仅本地主机测试):

  1. /blog路由pages/blog.js正常工作

  2. /const-string-a1b2c3d4404的路由

如何在重定向到404之前捕获匹配此字符串的url ?

对于其他可能希望这样做的人,我最终使用自定义404.js文件来处理这样的重定向。

pages/404.js:

import {useRouter} from 'next/router';
import { useEffect, useState } from 'react';
export default function Custom404() {
const router = useRouter();
const [route, setRoute] = useState('');
var regex = new RegExp(/const-string-([0-9A-Za-z-]+)/gi);
var matches = route.match(regex);
useEffect(() => {
setRoute(router.asPath);
window.location.href = (matches ? "https://google.com/?q=" + matches[0] : '/?404');
}, [router, matches]);
return <h1>Redirecting...</h1>
}

最新更新