skip to Main Content

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!

3

Answers


  1. 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 🙂

    Login or Signup to reply.
  2. The following might be simpler and does the same as far as I can see:

    redirect: [
        {
            from: '^(\/[^\?]*[^\/])(\?.*)?$',
            to: '$1/$2',
        },
    ],
    
    Login or Signup to reply.
  3. 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 + '/';
          }
        }
      ],
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search