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)
以下将把所有不存在的路径重定向到小写路径。如果找不到路径,则会显示 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。
| 归档时间: |
|
| 查看次数: |
1928 次 |
| 最近记录: |