【发布时间】:2019-02-21 08:43:32
【问题描述】:
出于 SEO 的目的,我被要求在我的 nuxt 项目的每条路线的末尾添加一个斜杠。例如 myapp.com/company 应该是 myapp.com/company/ 在 Nuxt 中是否有一种干净的方法可以做到这一点?
【问题讨论】:
出于 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);
if (redirect) {
console.log(`redirect: ${redirect.from} => ${redirect.to}`);
res.writeHead(301, { Location: redirect.to });
res.end();
} else {
next();
}
}
最后我在根文件夹中的 301.json 中写入我想要的重定向:
[
{ "from": "/company", "to": "/company/" }
]
编辑:问题留在这里,因为应用程序链接的代码内部没有斜线,因此机器人的索引将使用它....我需要找到更好的解决方案。
【讨论】:
我也在做这个要求。我用下面的方法做任务,不知道对不对。
两步:
Nginx 重写 url,即在 url 的末尾添加斜线 '/',即 url 不是以斜线结尾的。在这种情况下,http 请求被发送到 Web 服务器。
在另一种情况下,如果请求(或链接路由)在前端进行路由,则该请求不会向 Web 服务器发送 http 请求。然后像这样添加一个名为 addSlash.js 的中间件文件:
function isThereSlashEnd(path) {
let isSlash = true
if (path) {
let length = path.length
isSlash = path[length-1] == '/' ? true : false
console.log('??? path222: ', path, path[length-1], isSlash)
}
return isSlash
}
export default function({ req, store, route, redirect }) {
/**
* Add slash of '/' at the end of url
*/
let isSlash = isThereSlashEnd(route.fullPath)
console.log('??? path111: ', isSlash, route.fullPath, process.client)
if (!isSlash) {
if (process.client) {
window.location.href = route.fullPath + '/'
console.log('??? path: ', isSlash, route.fullPath, process.client, window.location)
}
}
}
通过以上两步,完成任务。
【讨论】: