在 Next.js 中将 URL 从大写重定向到小写

Yuv*_*evy 6 javascript http-status-code-301 reactjs next.js vercel

我需要将访问者从 重定向/Contact/contact

当我按照文档中的描述进行操作时,我得到了一个无限重定向循环。

这是我尝试过的:

// next.config.js
async redirects() {
    return [
        {
            source: '/Contact',
            destination: '/contact',
            permanent: true
        }
    ]
}
Run Code Online (Sandbox Code Playgroud)

ch3*_*n1k 18

使用Next.JS >=12,您可以使用自定义中间件。

middleware.js在根文件夹下创建名为的文件并使用以下代码:

import { NextResponse } from 'next/server';

const Middleware = (req) => {
  if (req.nextUrl.pathname === req.nextUrl.pathname.toLowerCase())
    return NextResponse.next();

  return NextResponse.redirect(new URL(req.nextUrl.origin + req.nextUrl.pathname.toLowerCase()));
};

export default Middleware;
Run Code Online (Sandbox Code Playgroud)

  • 不要使用此方法。`new URL` 非常慢。 (3认同)

And*_*rew 3

以下将把所有不存在的路径重定向到小写路径。如果找不到路径,则会显示 404。

import { useEffect } from 'react'
import { useRouter } from 'next/router'
import Error from 'next/error'

export default function ResolveRoute() {
  const router = useRouter()

  useEffect(() => {
    const { pathname } = router;

    if (pathname !== pathname.toLowerCase()) {
      router.push(pathname.toLowerCase())
    }
  },[router])

  return <Error statusCode={404} />
}
Run Code Online (Sandbox Code Playgroud)

将此文件名作为“[route].js”放在页面文件夹的根目录中将起到包罗万象的作用(除非该页面存在)。这将重定向到小写。如果已经准备好小写,则表示该页面是 404。

  • 这似乎总是返回 404 错误页面,这是有道理的,因为“return &lt;Error ... /&gt;”是无条件的。另请注意,“pathname”现在包含“params”,因此您需要将“.toLowerCase()”应用于“router.asPath”。最后,将其修改为“return null”将使用户到达小写路径,但不会解决任何 SEO 问题,这需要 301/302 重定向。 (2认同)