Published on

Redirect URL to Lowercase with Next.js Middleware

Authors

Recently, I moved my blog from Gatsby 2 to Next.js based blog. And noticed that I've started getting lots of 404 suddenly.

Surprisingly, the URLs that I've seen in the error log and the one that I've for that individual blog post are different. And its cases were mixed.

So to fix that, I've made sure that going forward all the URL needs to be in lowercase and also make sure to redirect the existing URL with mixed cases to the proper one.

I tried to do that using next.config.js but ended up breaking the site. It showed me some sort of infinite loop if I tried to redirect the URL from mixed case to lowercase.

Then, I came across the middleware approach.

With this approach, the URL will be redirected from any case /blog/nextjs-getServerSideProps-ip-address to lowercase like /blog/nextjs-getserversideprops-ip-address

Here's how to do it.

// middleware.js
// place this file in root directory where you've next.config.js not inside pages.

import { NextResponse } from 'next/server'

export const config = {
    matcher: '/blog/:path*',
}

const Middleware = (req) => {
    const { pathname, origin } = req.nextUrl

    if (pathname === pathname.toLowerCase()) {
        return NextResponse.next()
    }

    // By using URL, we're making sure that query string stays as it is.
    return NextResponse.redirect(new URL(origin + pathname.toLowerCase()))
}

export default Middleware

Reference

Happy fixing URLs!