ru
Remove trailing slash and create 301 redirect in Nuxt 3

Remove trailing slash and create 301 redirect in Nuxt 3

As promised in the previous article, I'm starting to publish a series of small notes on Nuxt customization. I will start with removing the trailing slash at the end of the page URL.

Why remove the slash?

For SEO (Search Engine Optimization) it makes no difference whether a page has a closing slash or not. There is only one rule: all pages on the site must be consistent. In other words, either there is a slash all around the site, or it is not. The presence of both options results in duplicate pages in the search engine. For Google and Yandex page with and without slash are two different pages.

On the previous engine Eleventy, trailing slashes were enabled by default. I personally like links without a slash at the end. I didn't bother with it at the time, but now I've decided to do it the way I like.

Options for solving this

For Nuxt 2 there is a separate router setting trailingSlash, to control the trailing slash. In Nuxt 3 it has been removed. So let's find another solution.

First I tried to do it via Netlify hosting settings. I couldn't find an easy solution. There is an option that discards the ending slash, but it doesn't send a 301 redirect code (resource moved to a new address), which is not suitable for me. The 301 code is extremely important for SEO and search engines — it reduces the number of duplicated pages in the search index.

In the Netlify interface, you can find this option here:

Build and Deploy → Post processing → Pretty Urls → Enable

We can't do it using the Netlify redirect file. So let's write our own middleware for Nuxt.

Writing custom middleware

First of all, what is middleware?

Middleware is a function that can be run before rendering a page. In universal rendering mode, middleware will be called once on the server side (at the first request to the Nuxt instance) and on the client side when navigating to the next routes.

Create a file @/middleware/trailing-slash.global.ts and put the following into it:

export default defineNuxtRouteMiddleware(({ path, query, hash }) => {
  if (path === '/' || !path.endsWith('/')) return

  const nextPath: string = path.replace(/\/+$/, '') || '/'
  const nextRoute = { path: nextPath, query, hash }

  return navigateTo(nextRoute, { redirectCode: 301 })
})

In this code, if the page is the homepage or the URL does not contain a trailing slash, the function stops. If it does, it redirects to a URL without the slash and gives a 301 code.

That's basically all. Pretty simple customization that will improve SEO performance for your site on Nuxt 3.


References:

Last Updated: