Remove the slash (/) at the end of my routee

281 Views Asked by At

I would like to know some way to remove the slash at the end of the routes in Nuxtjs.

I have tried with the @nuxtjs redirect-module and setting the trailingSlash property to false, but when I do it, far from removing the slash, it puts many more at the end.

For example: Original path: "myroute/" Path I want: "myroute" Path that appears when putting some of those changes: "myroute///////////////////"

1

There are 1 best solutions below

0
Ali Bahrami On

The behavior you're describing seems unusual and might be caused by a combination of configurations or other plugins affecting the routes. However, here's a way you can handle trailing slashes using a middleware:

add a middleware/remove-trailing-slash.js :

export default function({ route, redirect }) {
  if (route.path !== '/' && route.path.endsWith('/')) {
    let newPath = route.path.slice(0, -1);
    redirect(301, newPath);
  }
}

This checks if the path ends with a slash and redirects to the same path without it.

Then, all you have to do is to register it in nuxt.config.js:

export default {
  router: {
    middleware: ['remove-trailing-slash']
  }
}

Hope this helps!