在 Nuxt.js 中每条路由的末尾添加一个 slask/ [英] Add a slask / at the end of every routes in Nuxt.js
问题描述
出于 SEO 的目的,我被要求在我的 nuxt 项目的每条路线的末尾添加一个斜线.例如 myapp.com/company 应该是 myapp.com/company/在 Nuxt 中是否有一种干净的方法来做到这一点?
好的,我通过在服务器端的中间件中编写重定向找到了解决方案,所以首先我添加到 nuxt.config.js 中:
serverMiddleware: ["~/servermiddleware/seo.js"],
然后我创建了这个文件/servermiddleware/seo.js :
const redirects = require('../301.json');module.exports = function (req, res, next) {const redirect = redirects.find(r => r.from === req.url);如果(重定向){console.log(`重定向:${redirect.from} => ${redirect.to}`);res.writeHead(301, { Location: redirect.to });重发();} 别的 {下一个();}}
最后我在根文件夹中的 301.json 中写入我想要的重定向:
<预><代码>[{ "from": "/company", "to": "/company/" }]问题留在这里,因为应用程序链接的代码内部没有斜线,因此机器人的索引将使用它......我需要找到更好的解决方案.
For a purpose of SEO i've been asked to add a slash at the end of every routes of my nuxt project. For example myapp.com/company should be myapp.com/company/ Is there a clean way to do that in Nuxt ?
ok i found the solution by writting a redirection in a middleware on serverside, so first i added to nuxt.config.js this :
serverMiddleware: ["~/servermiddleware/seo.js"],
then i created this file /servermiddleware/seo.js :
const redirects = require('../301.json');
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();
}
}
and finally i write the redirections i want in 301.json in the root folder:
[
{ "from": "/company", "to": "/company/" }
]
edit: a problem stay here because inside the code of the app links stays without slash so the indexation of robot will use it.... i need to find a better solution.
这篇关于在 Nuxt.js 中每条路由的末尾添加一个 slask/的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!