7

I am looking for a way to redirect all my URLs so that they all do not have a slash in the end. I have tried with https://www.npmjs.com/package/@nuxtjs/redirect-module, but it does not redirect correctly.

redirect: [
    {
      from: '\/$',
      to: (from, req) => req.url.replace(/\/$/, '')
    }
  ],

For example, to change such a url http://localhost:8080/item/test-slug/ This module redirects me to http://localhost:8080/item/test-slug/item/test-slug

Any insight will be welcome. Thanks!

1
  • looking for the same with ?fbclid=, no result yet ... Commented Feb 13, 2020 at 12:41

6 Answers 6

16

I've solved this problem using custom middleware. It redirects to url which don't have a slash in the end.

Create src/middleware/trailingSlashRedirect.js

export default function ({ route, redirect }) {
  if (route.path !== '/' && route.path.endsWith('/')) {
    const { path, query, hash } = route;
    const nextPath = path.replace(/\/+$/, '') || '/';
    const nextRoute = { path: nextPath, query, hash };

    redirect(nextRoute);
  }
}

Register it in nuxt.config.js:

export default {
  ...
  router: {
    middleware: 'trailingSlashRedirect',
  },
}

So you should not use any module to solve this problem. I think it's much better than using third party libs.

Sign up to request clarification or add additional context in comments.

6 Comments

Seemed to only work when adding trailingSlash: false to the router as well. Otherwise an error occurred (about duplicate redirection)
@tmarois you don't need to add trailingSlash: false, duplicate redirections will not occur due to custom middleware I mentioned above
thank you for this, works perfectly with my current set up that uses trailingSlash: false
Does anyone know why the trailing slash is added in the first place? Strangely, it only adds it to 3 pages on the site I am working on. I used trailingSlash: false and it does work when using the internal router but not on initial page load or reload.
Why do you need first condition in your 'if'? I removed it and left only second condition and it seems to work perfect (with trailingSlash: undefined).
|
5

You can remove trailing slash with Nuxt latest version(Available since v2.10) with below way: https://nuxtjs.org/api/configuration-router/#trailingslash

trailingSlash : Type: Boolean or undefined
Default: undefined
Available since: v2.10
ex:
router: {
  trailingSlash: false
}

Or with the older version of Nuxt You can use nuxt-trailingslash-module https://www.npmjs.com/package/nuxt-trailingslash-module

npm i nuxt-trailingslash-module

2 Comments

Ive tried. trailingSlash: false just does not work. no matter the version
This does not remove the trailing slash, it makes the route with the trailing slash not work (or the opposite). You still have to handle the redirect.
2

So the only solution I found so far isn't perfect.

Using the redirect-module , I added the following at the top of my redirects list:

{
  // eslint-disable-next-line
  from: '(?!^\/$|^\/[?].*$)(.*\/[?](.*)$|.*\/$)',
  to: (from, req) => {
    const base = req._parsedUrl.pathname.replace(/\/$/, '');
    const search = req._parsedUrl.search;
    return base + (search != null ? search : '');
  }
},

Also in nuxt.config.js I made sure to add the trailing slash configuration. (See the doc)

router: {
  trailingSlash: false
},

Note: It redirect all URLS ending with '/' with query parameters, but it doesn't match the home page '/' (which seems to be handled somehow)

The following will redirect the following:

  • '/blog/' to '/blog'
  • '/blog/?a=b' to '/blog?a=b'
  • '/blog/foo/' to '/blog/foo'
  • '/blog/foo/?a=b' to '/blog/foo?a=b'
  • '/' to '/'. --> won't work
  • '/?a=b' to '/?a=b'. --> won't work

I made a test list available here


Explanation of the regex

It might not be perfect since I'm not a Regex expert but:

'(?!^\/$|^\/[?].*$)(.*\/[?](.*)$|.*\/$)'

It's broken it 2 pieces: 1 exclusion, and 1 inclusion.

The exclusion: (?!^\/$|^\/[?].*$), consist of a check to exclude standalone trailing comma (/) or standalone trailing comma with query string /?foo=bar routes. It's used mainly for the home page.

The inclusion: (.*\/[?](.*)$|.*\/$), consists of checking for the trialing comma (/blog/) or a trailing comma with query string (/blog/?foo=bar)

1 Comment

this is great! i think the regex could be simplified to: from: '.{1,}\/([?].*)?$'. this matches any path that has at least 1 character before a trailing slash at the end - with an optional querystring.
1

For those who are looking for a solution working on Nuxt 3, you have to use a middleware.

Create a file named trailingSlash.global.js in the middleware directory and copy/paste this inside :

export default defineNuxtRouteMiddleware((to) => {
  if (to.path.slice(-1) === '/') {
    return navigateTo({...to,
      path: to.path.slice(0, -1)
    })
  }
});

4 Comments

What's the point of this? Trailing slashes are being removed automatically in Nuxt 3.
It doesn't, I have three project running on Nuxt 3 and none of them removes the trailing slash automatically.. Could be because I use the "pages:extend" hook, I don't really know..
500 Infinite redirect in navigation guard
For Nuxt 3 with SSR on Apache, the solution is in your .htaccess file as described here stackoverflow.com/a/77699881/1454622 . The trick is that we want to display no trailing slash BUT ALSO serve that directory's index.html file.
0

In nuxt.config.js as @Hardik Shah and @tsnkff says

router: {
  trailingSlash: false
},

For other needs use ufo package https://github.com/unjs/ufo#withouttrailingslash

withoutTrailingSlash Ensures url does not ends with a trailing slash

// Result: /foo
withoutTrailingSlash('/foo/')
// Result: /path?query=true
withoutTrailingSlash('/path/?query=true', true)

withTrailingSlash Ensures url ends with a trailing slash

// Result: /foo/
withTrailingSlash('/foo')
// Result: /path/?query=true
withTrailingSlash('/path?query=true', true)

and other helpful functions are in unjs/ufo package that created by nuxt team and is used in nuxt code also.

Comments

0

For those who are having problem with the top answer (creating custom middleware to redirect) using Nuxt 2.15.8. If you are getting the too many redirects error, it may be caused by Nuxt doing its own internal redirection to end-slash variant (from test-slug to test-slug/). Nuxt decides to add a slash when you have the same name folder in the static folder as you page filename.

The solution is renaming either of those.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.