redirect-module icon indicating copy to clipboard operation
redirect-module copied to clipboard

Force Trailing Slash - with params

Open Jesus82 opened this issue 5 years ago • 7 comments

Hi, I am looking for a way to redirect all my urls in order to have them all end in slash. So far I was able to do that, but that method fails when there are params (as in that case the trailing slash should go after the url and before the params).

I opened a thread in StackOverflow, and there is an answer that works in plain regex, but doesn't do the trick with this module (it doesn't redirect at all)

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]
        }
     }
]

You can see the more detailed discussion here https://stackoverflow.com/questions/56100693/nuxt-js-add-trailing-slash-to-urls-with-params/56211756?noredirect=1#comment99088301_56211756

Jesus82 avatar May 22 '19 09:05 Jesus82

The from regex looks OK to me assuming that URL passed to it doesn't contain protocol (I think that's correct assumption looking at this module's code).

Are you sure the to function is not triggered?

rchl avatar May 23 '19 09:05 rchl

I'm trying it in local and it's not redirecting at all, while the previous version (see this closed issue did work properly (when there were no params in the URL).

Jesus82 avatar May 23 '19 09:05 Jesus82

That regexp uses negative lookbehind feature which is supported from Node 9. Maybe that was the problem? Otherwise it should be correct. Tested here - https://regex101.com/r/5WbpEU/1 (with some escaping removed as input is a regexp object, not a string on that site.

rchl avatar Aug 15 '19 19:08 rchl

@manniL I think you can close this, it's a question about how to do regexp

ricardogobbosouza avatar Aug 26 '19 21:08 ricardogobbosouza

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

best solution

hartwm avatar Mar 05 '20 17:03 hartwm

The crap thing about redirect: [] is that is assumes a server in the loop. The thing that drew us to Nuxt was static rendering the site and hosting it in S3. I still have no idea if there's a clean and resilient way to manage redirects on the client side when there's no server...

askdesigners avatar Jul 02 '20 08:07 askdesigners

Create a middleware and put your logic there (based on context.route).

(You might hit some issue with middleware not being called on initial navigation though...)

rchl avatar Jul 02 '20 08:07 rchl