Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Nuxt.js - add trailing slash to URL's with params

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!

like image 665
Joe82 Avatar asked May 12 '19 15:05

Joe82


2 Answers

The following might be simpler and does the same as far as I can see:

redirect: [
    {
        from: '^(\\/[^\\?]*[^\\/])(\\?.*)?$',
        to: '$1/$2',
    },
],
like image 146
maikel Avatar answered Oct 06 '22 14:10

maikel


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 :)

like image 36
niccord Avatar answered Oct 06 '22 13:10

niccord