Joe82
Joe82

Reputation: 1251

Nuxt.js - force trailing slash at the end of all urls

I'm looking for a way to make sure that all of my urls end with a trailing slash (so first check if there is already a trailing slash at the end, and if not add one).

I have tried with nuxt-redirect-module, and it works adding the slash but then it leads to an infinite redirect

redirect: [
  {
    from: '^(.*)$',
    to: (from, req) => {
      let trailingUrl = req.url.endsWith('/') ? req.url : req.url + '/'
      return trailingUrl
    }
  }
]

Any insight will be welcome. Thanks!

Upvotes: 8

Views: 11593

Answers (3)

GerritElbrink
GerritElbrink

Reputation: 352

I had the same problem, but I didn't want to use the redirects. I tried a lot of solutions, but finally it turned out that adding a double slash to the routing path had the desired effect:

  router: {
    prefetchLinks: false,
    middleware: 'navigation',
    routeNameSplitter: '/',
    extendRoutes(routes, resolve) {
      routes.push(
        {
          name: 'kaufen',
          path: '/kaufen//',
          component: resolve(__dirname, 'pages/listing/index.vue'),
        },
        {
          name: 'mieten',
          path: '/mieten//',
          component: resolve(__dirname, 'pages/listing/index.vue'),
        },

This results in:

https://example.com/kaufen/?alternate=true&ignoreToplisting=false

It seems very hacky, but it does the trick!

Upvotes: 1

maikel
maikel

Reputation: 1165

The following regex handles query string as well:

redirect: [
    {
        from: '^(\\/[^\\?]*[^\\/])(\\?.*)?$',
        to: '$1/$2',
    },
],

Upvotes: 9

antonku
antonku

Reputation: 7665

You can try to match only those URLs that do not end with a slash:

redirect: [
    {
        from: '^.*(?<!\/)$',
        to: (from, req) => req.url + '/'
    }
]

Upvotes: 5

Related Questions