【问题标题】:How to get Stack Overflow SEO friendly URL structure in Nuxt.js?如何在 Nuxt.js 中获得 Stack Overflow SEO 友好的 URL 结构?
【发布时间】:2021-12-04 06:15:51
【问题描述】:

Stack Overflow 具有以下 URL 结构 stackoverflow.com/questions/{question ID}/{question title},如果您输错了 {question title},只要您有正确的 {question ID},您将被永久重定向到正确的 URL 301

假设我同时拥有idslug,我怎样才能使堆栈溢出在Nuxt.js 中的URL 结构与SSR 相同?

编辑:显然 URL 结构被称为Clean URL

我曾尝试使用带有 pages/x/_.vue 的完全动态 URL,但这会为每个请求提供一个“新”页面,并且不会提供 301 重定向。

This post 建议如下:/questions/8811192/question-title 可以重写为/mywebsite.php?id=8811192&convention=questions。因此,如果我可以将 /qeustions/{id}/{title} 解释为 /qeustions/{id},我猜我可能已经完成了一半。

标签: vue.js redirect nuxt.js seo friendly-url


【解决方案1】:

以下内容对我有用,但我不确定它是否与 Stack Overflow URL 结构的工作方式完全相同。

我正在使用async asyncData 从数据库中获取内容,您可以访问 contextredirectreqres 作为参数,您可以执行 301 重定向。

首先我在我的文件夹中使用unknown dynamic nested routes,例如/pages/folder/_.vue。它将捕获所有路线,包括domain.com/folder/{id}domain.com/folder/{id}/{title}

要获取请求的 url 中的 ID,您可以拆分 pathMatch 并获取第一个元素,例如 params.pathMatch.split('/')[0]

然后我使用 id 从数据库中获取内容,在我的例子中是 Strapi。喜欢这个await $strapi.findOne('contentType', id)

之后,我们可以像/folder/${data.id}/${data.slug} 这样创建我们想要的实际 URL。注意:data.slug 可以替换为data.title,可以转换为 URL 友好字符串。

最后我们可以将用户请求的 URL 与内容的实际 URL if(route.fullPath !== actualURL) 匹配,如果请求的 url 不一样,我们可以使用 redirect(301, actualURL) 执行重定向。

我的整个代码:

async asyncData({ redirect, req, route, app, $strapi, error, params }) {
    try {
        const recipeID = params.pathMatch.split('/')[0];
        const matchingRecipe = await $strapi.findOne('recipes', recipeID);
        const correctPath = `${app.localePath('recipes')}/${matchingRecipe.id}/${matchingRecipe.slug}`;
        if(route.fullPath !== correctPath) {
            console.log(`Redirect: ${route.fullPath} => ${correctPath}`);
            redirect(301, correctPath);
        }
        return {
            recipe: matchingRecipe
        }
    } catch(e) {
        console.log(e)
        error({ statusCode: e.statusCode, message: e.original });
    }
    
},

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-11-06
    • 1970-01-01
    • 1970-01-01
    • 2010-11-05
    • 2012-10-29
    • 2013-01-20
    相关资源
    最近更新 更多