Reputation: 1251
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
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
Reputation: 1165
The following regex handles query string as well:
redirect: [
{
from: '^(\\/[^\\?]*[^\\/])(\\?.*)?$',
to: '$1/$2',
},
],
Upvotes: 9
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