Published on

Next.js URL Redirects: From Trailing Slashes to No Slashes

Authors

Recently, I've moved my blog from Gatsby 2 to Next.js based one. And noticed that after some time I've started getting canonical URL-related errors in Google Webmaster.

Apparently, my old version of my blog has the URL with a trailing slash and I prefer the one without a trailing slash.

As a result, both things got indexed in Google and it has raised duplicate content errors in it.

For example, in terms of search engines https://nesin.io/about/ URL is different than https://nesin.io/about

In terms of SEO, both are fine. But you should follow only one thing with or without Trailing Slashes

Since most of my old URLs might have been indexed with trailing slashes. I thought to redirect them to URL without slashes instead so that it does not get flagged as duplicate content (and hopefully new URL gets indexed in the search engine)

There are various ways to do that like for example, with the help of Next.js middleware and things.

But configuring that in next.config.js seems to be a simple and straight forward way to do it.

Here's how to do it.

// next.config.js
module.exports = {
  async redirects() {
    return [
        // Redirect /blog/*/ to /blog/*
      {
            source: '/blog/:slug*/',
            destination: '/blog/:slug',
            permanent: true,
        },
    ]
  },
}

Happy fixing slashes!