HB's Thoughts

I try to think really hard.


Removing the trailing slash from the URLs in Nuxt

Every page on your website should have unique content. If you have a second page with the same content, the weight of the information for the search engines is divided between the two, and this greatly reduces their chances of appearing earlier in the search results.

If you have a page that loads at https://example.com/page, it is very likely that the same page will also load at https://example.com/page/. From our point of view, this is the same page, but for search engines, these are two different addresses. They expect to have different content on them.

One of the ways to tell the search engines which content should be considered is the canonical addresses of the pages. I will pay attention to another - to tell the search engines that the 'wrong' address has been moved. As you understand, this should happen even before the crawling machine loads our page. In Nuxt, this can be done with a small middleware.

// middleware/remove-trailing-slash.global.ts

export default defineNuxtRouteMiddleware((to) => {
  if (to.path === "/" || !to.path.endsWith("/")) return; // -->

  const removedSlash = to.path.replace(/\/+$/, "") || "/";
  const seoRoute = { path: removedSlash };

  return navigateTo(seoRoute, { redirectCode: 301 });

We add global to the middleware's name to run it before loading each page, without the pages needing to call it explicitly.

If you have an opinion or questions about the article, don't hesitate to share them.

Join the open discussion on GitHub.

Competence: Pro
Tags: NuxtSEO