'How to make path for pages in NextJS case insensitive

I have a file under the pages folder named about.tsx. So the path for the page is /about and I'm able to access the page by visiting example.com/about. However, if I visit example.com/About, it will redirect to a 404 page.

I've checked the Nextjs repo, seems like this is the expected behavior. Therefore, is there a workaround that can make the path case insensitive so that example.com/About will also work and direct users to the /about page?



Solution 1:[1]

With using next v12

There are a lot of similar questions here that has this answer already. I'd like to note that this answer is handling redirecting with the url parameters by adding this after the pathname:

${request.nextUrl.search}

Add a new file in /pages named _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()}${request.nextUrl.search}`);
}

Solution 2:[2]

I agree that's Next.js's behavior, they only handle exact page name about instead of both about & About using the same file page/about.tsx

But the solution is you keep implementing a main page (e.g: about.tsx) and setup other pages to redirect to that page (e.g: About -> about) following this guide https://nextjs.org/docs/api-reference/next.config.js/redirects

// next.config.js
module.exports = {
  async redirects() {
    return [
      {
        source: '/About',
        destination: '/about',
        permanent: true,
      },
    ]
  },
}

// Set permanent:true for 301 redirect  & clean SEO!

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 nghiaht