Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

vue.js

nuxt.js

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!

like image 472
Joe82 Avatar asked Jan 24 '19 12:01

Joe82


2 Answers

The following regex handles query string as well:

redirect: [
    {
        from: '^(\\/[^\\?]*[^\\/])(\\?.*)?$',
        to: '$1/$2',
    },
],
like image 125
maikel Avatar answered Sep 25 '22 02:09

maikel


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

redirect: [
    {
        from: '^.*(?<!\/)$',
        to: (from, req) => req.url + '/'
    }
]
like image 26
antonku Avatar answered Sep 22 '22 02:09

antonku