How to add 301 redirects to NUXT

Viewed 3424

I have a NUXT project which i'm trying to add 301 redirect to. I've tried a few different approaches, but nothing works. If I go to the old URL I get a 404 page.

Whats the best way to add redirects to a Nuxt project?

Any help would be appreciated.

 const redirects =
 [
   { from: 'https://www. example.com/article/new-guidelines-new-normal-new-opportunities-new-working-environments', to: 'https://www. example.com' },
   { from: 'https://www. example.com/article/vetting-candidate-why-its-a-no-brainer', to: 'https://www. example.com' },
   { from: 'https://www. example.com/job-alerts', to: 'https://www. example.com' },
   { from: 'https://www. example.com/jobs', to: 'https://www. example.com' },
   { from: 'https://www. example.com/news', to: 'https://www. example.com' },
   { from: 'https://www. example.com/login', to: 'https://www. example.com' },
   { from: 'https://www. example.com/cv-upload', to: 'https://www. example.com/#submit-cv' },
   { from: 'https://www. example.com/expertise', to: 'https://www. example.com/our-expertise' }
 ]
 
  module.exports = function (req, res, next) {
   const redirect = redirects.find(r => r.from === req.url)
   if (redirect) {
     console.log(`redirect: ${redirect.from} => ${redirect.to}`)
     res.writeHead(301, { Location: redirect.to })
     res.end()
   } else {
     next()
   }
 }

// nuxt.connig.js

  serverMiddleware: [
    { path: "/api/redirects", handler: "~/api/redirects/index.js" },
  ],
2 Answers

You can create a serverMiddleware that does the job.

// nuxt.config.js
serverMiddleware: [{ 
      path: '/',
      handler: './serverMiddleware.js'
  }]
// serverMiddleware.js
export default (req, res, next) => {
  // detect urls you'd like to redirect
  // call res.redirect(CODE, NEWURL)

  if (req.url === '/some-page/') {
    res.writeHead(301, { Location: 'redirect-page' });
    res.end();
  } else {
    next();
  }
}

You can also use the Nuxt Redirect Module

// nuxt.config.js
redirect: [
  { from: '^/myoldurl', to: '/mynewurl', statusCode: 301 }
]
Related