---
title: "如何使用 Astro 404 頁面重定向正確的文章頁面？"
description: "例如【【翻譯】前端性能優化必備工具清單】，這是我在2017年翻譯的文章：https://calpa.me/2017/06/19/front-end-performance-check-list-for-production-in-chinese/應該重導向到https://calpa.me/blog/front-end-performance-check-list-for-produc…"
slug: "how-to-handle-old-404-redirects-with-astro-ssr-for-blog-posts"
date: 2023-11-30T00:00:00.000Z
url: https://calpa.me/blog/how-to-handle-old-404-redirects-with-astro-ssr-for-blog-posts/
---

例如【【翻譯】前端性能優化必備工具清單】，這是我在 2017 年翻譯的文章： [https://calpa.me/2017/06/19/front-end-performance-check-list-for-production-in-chinese/](/blog/front-end-performance-check-list-for-production-in-chinese/) 應該重導向到 [https://calpa.me/blog/front-end-performance-check-list-for-production-in-chinese/](/blog/front-end-performance-check-list-for-production-in-chinese/)

## 利用 Astro SSR 優化性能和用戶體驗

使用 Astro SSR 時，我們可以將一些關鍵邏輯移到伺服器端執行，從而提高網站的性能並減少用戶等待時間。這特別有助於處理需要根據路徑查找或處理內容的情況，如解決 404 錯誤問題。這有助於提供更流暢的用戶體驗，確保網站能夠快速響應用戶的需求。

## 解決方案：根據當前網址的路徑來查找相關的內容條目

以下代碼的主要功能是根據當前網址的路徑，查找相對應的博客內容條目（文章）。如果找到相符的文章，則會將用戶重定向到該文章頁面。如果找不到相符的文章，則會顯示一個友好的 404 錯誤頁面，以改善用戶體驗。

以下是代碼片段的示例：

```javascript
import { getEntry } from "astro:content";

const pathname = Astro.url.pathname;

const array = pathname.split("/").filter((x) => x);

const maybe_slug = array[array.length - 1];

const post = await getEntry({
  collection: "blog",
  id: maybe_slug, // Astro 5+ 改用 id（Astro 4 及以前為 slug）
});

// 如果找到相應的內容條目，則將用戶重定向到正確的文章頁面。
if (post !== undefined) {
  return Astro.redirect(`/blog/${maybe_slug}/`);
}
```

首先，獲取當前網址的路徑，然後解析該路徑以獲得可能的文章 slug。接下來，使用 `getEntry` 函數來查找博客集合中的相應內容條目。如果找到該條目，則會重定向到正確的文章頁面。如果未找到條目，則會顯示 404 錯誤頁面。
