Reputation: 1251
This question is based in this previous one
I want all my URL's to end with slash for SEO reasons. So far I have this function working with nuxt-redirect-module
redirect: [
{
from: '^.*(?<!\/)$',
to: (from, req) => req.url + '/'
}
]
This checks the url, and adds a /
at the end in case that there is not. The problem is when the url has params at the end.
So right now, this redirects
https://example.com/folder
to
https://example.com/folder/
(intended behaviour)
But with params, right now it works like this:
https://example.com/folder?param=true
to
https://example.com/folder?param=true/
(it adds the /
after the params)
QUESTION
Which would be the way to make it so it would redirect instead from
https://example.com/folder?param=true
to
https://example.com/folder/?param=true
(so it would add the /
at the end of the url but before the params)
Thanks in advance!
Upvotes: 11
Views: 4262
Reputation: 1
I wrote it like this. This code catch all unsigned urls ? and / at the end of the line. I think that's enough
redirect: [
{
from: '^(?!.*\\?).*(?<!\\/)$',
to: (from, req) => {
return req.url + '/';
}
}
],
Upvotes: 0
Reputation: 1165
The following might be simpler and does the same as far as I can see:
redirect: [
{
from: '^(\\/[^\\?]*[^\\/])(\\?.*)?$',
to: '$1/$2',
},
],
Upvotes: 2
Reputation: 844
redirect: [
{
from: '^[\\w\\.\\/]*(?<!\\/)(\\?.*\\=.*)*$',
to: (from, req) => {
const matches = req.url.match(/^.*(\?.*)$/)
if (matches.length > 1) {
return matches[0].replace(matches[1], '') + '/' + matches[1]
}
return matches[0]
}
}
]
Check the first regex here: https://regex101.com/r/slHR3L/1
Thanks to @Seybsen for the final hint :)
Upvotes: 2