我有一个 NUXT 项目,我正在尝试向其中添加 301 重定向。我尝试了几种不同的方法,但没有任何效果。如果我转到旧 URL,我会得到一个 404 页面。
将重定向添加到 Nuxt 项目的最佳方法是什么?
任何帮助将不胜感激。
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" },
],
答案 0 :(得分:2)
您可以创建一个服务器中间件来完成这项工作。
// 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();
}
}
您也可以使用 Nuxt Redirect Module
// nuxt.config.js
redirect: [
{ from: '^/myoldurl', to: '/mynewurl', statusCode: 301 }
]
答案 1 :(得分:0)
检查https://expressjs.com/en/api.html#res.redirect 然而 serverMiddleware 属性在 vue-server-renderer 之前运行服务器端,可用于服务器特定的任务,如处理 API 请求或服务资产 我的方法是路由中间件,在客户端或 SSR 中由 Vue 在每条路由之前调用 https://nuxtjs.org/docs/2.x/components-glossary/pages-middleware