在NextJS中重定向通配符路线

发布于 2025-02-08 06:36:32 字数 761 浏览 0 评论 0原文

在部署新的NextJS应用程序时,需要从旧的非nextjs网站保存一些旧路线。

/const-string- [longiqu-hash]当前用于HTTPD Conf Redirect:

ex。 重写 ^const-string - (。*)$ https://google.com?q=const-string-qure-quly-qur-quny1 [l,nc]

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

所需的行为:

  1. /blog路由pages/blog.js

  2. /const-string-a1b2c3d4路由到https://google.com ?q = const-string-a1b2c3d4

当前行为(到目前为止仅Local-Host测试):

  1. /blog路由pages/blog.js按预期工作

  2. /const-string-a1b2c3d4路由到404

在重定向到404之前,如何捕获匹配该字符串的URL?

In deploying a new NextJS app there are some legacy routes that need to be preserved from the old, non-NextJS site.

/const-string-[long-unique-hash] is used currently for a httpd conf redirect:

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

How can I preserve NextJS routing, but allow for legacy routes matching the path: /const-string-*?

Desired behavior:

  1. /blog routes pages/blog.js

  2. /const-string-a1b2c3d4 routes to https://google.com?q=const-string-a1b2c3d4

Current behavior (only localhost testing so far):

  1. /blog routes pages/blog.js works as expected

  2. /const-string-a1b2c3d4 routes to 404

How can I catch urls matching this string before it's redirected to 404?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

萌化 2025-02-15 06:36:32

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

页面/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>
}

For others that may wish to do the same, I ended up using a custom 404.js file to handle redirects like this.

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>
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文