在部署新的NextJS应用程序时,需要从旧的非NextJS站点中保留一些遗留路由。
/const-string-[long-unique-hash]
目前用于httpd配置重定向:
交货。RewriteRule ^const-string-(.*)$ https://google.com?q=const-string-$1 [L,NC]
如何保留NextJS路由,但允许遗留路由匹配路径:/const-string-*
?
所需行为:
/blog
routespages/blog.js
/const-string-a1b2c3d4
到https://google.com?q=const-string-a1b2c3d4
的路由
当前行为(目前仅本地主机测试):
/blog
路由pages/blog.js
正常工作/const-string-a1b2c3d4
到404
的路由
如何在重定向到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>
}