Reputation: 559
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" },
],
Upvotes: 12
Views: 15073
Reputation: 5164
For Nuxt 3 you can use the routeRules
setting in your nuxt.config.ts
.
nuxt.config.ts
export default defineNuxtConfig({
routeRules: {
"/from": {
redirect: {
to: "/to",
statusCode: 301,
},
},
},
});
For more config options see https://nitro.unjs.io/config/#routes
Upvotes: 10
Reputation: 639
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 }
]
Upvotes: 14
Reputation: 51
check https://expressjs.com/en/api.html#res.redirect however serverMiddleware property runs server-side before vue-server-renderer and can be used for server specific tasks like handling API requests or serving assets my approach is routes middleware which are called before each route by Vue in Client Side or SSR https://nuxtjs.org/docs/2.x/components-glossary/pages-middleware
Upvotes: 0