gpt4 book ai didi

nuxt.js - 如何将 301 重定向添加到 NUXT

转载 作者:行者123 更新时间:2023-12-05 01:06:49 26 4
gpt4 key购买 nike

我有一个 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" },
],

最佳答案

您可以创建一个服务器中间件来完成这项工作。

// 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 }
]

关于nuxt.js - 如何将 301 重定向添加到 NUXT,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68415572/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com