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

dgjrabp2  于 2023-08-04  发布在  其他
关注(0)|答案(7)|浏览(141)

我需要将访问者从/Contact重定向到/contact
当我按照in the docs描述的方式执行时,我得到了一个无限重定向循环。
这就是我所尝试的:

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

字符串

nbewdwxp

nbewdwxp1#

通过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;

字符串

pwuypxnk

pwuypxnk2#

下面的代码将把所有不存在的路径重定向到小写的路径。如果找不到路径,则会显示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} />
}

字符串
将此文件名作为“[route].js”放在pages文件夹的根目录中将充当catch all(除非该页面存在)。这将重定向到小写。如果已经准备好小写,则意味着页面是404。

ewm0tg9j

ewm0tg9j3#

虽然我很喜欢Andrew的回答,但这是在客户端,我更喜欢服务器端的解决方案。
以下是我在Andrew的评论启发下所做的:

import Custom404 from "./404";

export default function CatchAllRoutes({url}) {
    return <Custom404 />
}

export async function getServerSideProps(context) {
    const url = context.query.catch;
    const { res } = context;
    if (url !== url.toLowerCase()) {
        res.writeHead(307, {location: `/${url.toLowerCase()}`}) // 307 is temporary while 308 is permanent, choose your preference here..
        res.end();
    } 
    else {
        context.res.statusCode = 404;
    }
    return { props: { url } }; // Note: You don't need a prop, but the name of function requires one..
}

字符串
我将页面根目录下的文件命名为[catch].js。如果URL与项目中的任何页面都不匹配,并且URL不是小写的,则将其小写并重定向到那里,否则我们知道它是404,在这种情况下,我们给予状态代码404并呈现custom404组件。

oxosxuxt

oxosxuxt4#

来自Reddit https://www.reddit.com/r/nextjs/comments/hk2qmk/nextjs_routing_case_sensitivity_issue/fwt29n2?utm_source=share&utm_medium=web2x&context=3
我使用_error.js页面组件修复了它。就像这样:

import { hasUpperCase } from '../lib/string';

...

Error.getInitialProps = ({ asPath, err, res }) => {
  const statusCode = res ? res.statusCode : err ? err.statusCode : 404;

  if (asPath && hasUpperCase(asPath)) {
    res.writeHead(307, { Location: asPath.toLowerCase() });
    res.end();
  }

  return { statusCode };
};

export default Error;

字符串
我也更喜欢这样做的重定向像你的例子虽然。

ghhkc1vu

ghhkc1vu5#

我发现这个有用的链接,涵盖了这个问题的许多解决方案:https://www.youtube.com/watch?v=_vSMITiXAik方案1:
1.在您的next.config.js中使用rewirte功能

return [
      {
        source: "(c|C)(o|O)(n|N)(t|T)(a|A)(c|C)(t|T)",
        destination: "/Contact", // here you need to add the exact page contact or Contact
      },
    ];
  },

字符串
1.使用_middleware功能:在你的pages文件夹中添加一个_middleware.ts文件。

import { NextRequest, NextResponse } from "next/server";

export function middleware(request: NextRequest) {
  if (request.nextUrl.pathname === request.nextUrl.pathname.toLocaleLowerCase())
    return NextResponse.next();
  return NextResponse.redirect(
    `${request.nextUrl.origin}${request.nextUrl.pathname.toLocaleLowerCase()}`
  );
}


使用这种解决方案,您可能需要将页面重命名为小写。
1.使用中间件功能,为每个页面提供一个文件夹。
你需要保持_middleware.ts不变,你需要做这些步骤:

  • 创建一个文件夹contact所有小写.
  • 移动你的页面到这个文件夹里。
  • 添加一个index.ts指向您的页面。其内容应该是这样:
export { default } from "./contact";

  • 使用此扩展名重命名所有页面:.page.tsxpage.ts(如果使用typescript),.page.jsxpage.js(如果JavaScript)。
  • next.config.js中,如果使用typescript,则需要添加此pageExtensions: ["page.tsx", "page.ts"],如果使用JavaScript,则需要添加pageExtensions: ["page.jsx", "page.js"]

您需要为所有页面执行此操作。

yhxst69z

yhxst69z6#

这里有一个非常优雅的解决方案,也将携带任何搜索/查询参数:

import { NextResponse } from 'next/server';

const Middleware = (req) => {
  if (req.nextUrl.pathname !== req.nextUrl.pathname.toLowerCase()) {
    const url = req.nextUrl.clone()
    url.pathname = url.pathname.toLowerCase()
    return NextResponse.redirect(url)
  }
  return NextResponse.next();
};

export default Middleware;

字符串

55ooxyrt

55ooxyrt7#

当我遇到这个问题时,我注意到NextJS在路径后面附加了一个斜杠。当我在浏览器中查看我的网络控制台时,我看到状态代码交替为307和308的请求。当我在destination路径后面添加了一个斜杠后,我看到很多状态为307的请求,但仍然会出现错误。
一旦我在sourcedestination路径后面添加了一个斜杠,重定向就像预期的那样发生了:

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

字符串

相关问题