Stack Overflow 具有以下 URL 結構stackoverflow.com/questions/{question ID}/{question title},如果您輸入錯誤,只要您輸入正確的 URL,{question title}您將被永久重定向301到正確的 URL {question ID}。
假設我有兩個id和slug,我怎么能做出同樣的網址結構堆疊溢位,在Nuxt.js有SSR?
編輯:顯然 URL 結構被稱為Clean URL。
我嘗試使用帶有 的完全動態 URL pages/x/_.vue,但這為每個請求提供了一個“新”頁面,并且沒有提供 301 重定向。
這篇文章提出以下建議:/questions/8811192/question-title可以重寫為/mywebsite.php?id=8811192&convention=questions. 因此,如果我可以解釋/qeustions/{id}/{title}為只是/qeustions/{id}我想我可以做到一半。
uj5u.com熱心網友回復:
以下對我有用,但我不確定它是否與 Stack Overflow URL 結構的作業方式完全相同。
我正在使用async asyncData從資料庫中獲取內容,因為您可以訪問
背景關系和redirect,req并且res作為引數您可以執行301重定向。
首先,我像這樣在我的檔案夾中使用未知的動態嵌套路由/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)。
之后,我們可以像這樣創建我們想要的實際 URL /folder/${data.id}/${data.slug}。注意:data.slugculd 替換為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 });
}
},
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/334376.html
標籤:Vue.js 重定向 nuxt.js 搜索引擎优化 友好网址
