在 Nuxt.js 中每条路由的末尾添加一个 slask/ [英] Add a slask / at the end of every routes in Nuxt.js

查看:184
本文介绍了在 Nuxt.js 中每条路由的末尾添加一个 slask/的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

出于 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆