NuxtJS - Redirect all wrong url's to 404 page

2.2k views Asked by At

Yo,

I have a question becouse i can't solve it in my way. I need redirect all wrong urls ("example mywebsite.com/asdasdasdasd") to mywebsite.com/404. How can i do it? I try using a *.vue and _.vue in pages folder but when I try to type a wrong url my website crash on localhost either

1

There are 1 answers

0
Szabó Csaba On

If you use nuxt.js in universal mode (which means that you have server-side code as well), then you can use Nuxt.js serverMiddleware.

You could create a new /serverMiddleware/redirects.js file with the redirect logic:

const redirects =
[
  { "from": "/asdasdasdasd", "to": "/404" },      
]

module.exports = function (req, res, next) {
  const redirect = redirects.find(r => r.from === req.url)
  if (redirect) {
    console.log(`301 redirect: ${redirect.from} => ${redirect.to}`)
    res.writeHead(301, { Location: redirect.to })
    res.end()
  } else {
    next()
  }
}

Then add this as a serverMiddleware in nuxt.config.js:

serverMiddleware: [
  '~/serverMiddleware/redirects'
]

This is the simplest solution if you have some URLs to redirect. You could change this code to redirect all urls with a given pattern.