使用 Laravel Head 來設定網頁元標籤

使用 Laravel Head 來設定網頁元標籤
程式技術
•

前陣子 Laravel 團隊推出了全新的套件 Head,用來管理網頁上的 <head> 元素,你可以用它來設定標題與各種元標籤,其中包含社群分享用的 Open Graph 元標籤。這個套件一樣承襲了 Laravel 優雅的 API 設計,並支援 Livewire 與 Inertia.js,接下來就以我的個人專案為例,簡單的介紹 Head 套件的使用方式。

環境說明與安裝

接下來的範例會以我的筆記網頁為例,該網頁的前後端技術使用 Laravel、Inertia.js 與 Svelte,並且有開啟 Server Side Rendering。

首先使用 Composer 安裝 Head 套件:

composer require laravel/head

使用方式

在 AppServiceProvider.php 中設定預設的 Head:

public function boot(): void
{
    $this->configureHead();
}

protected function configureHead(): void
{
    // 預設會採用的 Head 設定,可以在 Controller 中覆寫
    Head::defaults(function (HeadBuilder $head): void {
        $head
            ->title(config('app.name'), suffix: ' - '.config('app.name'))
            // 設定 Canonical URL
            ->canonical()
            // 設定 Open Graph 元標籤
            ->og(
                type: OgType::Website,
                siteName: config('app.name'),
            )
            // 設定 X / Twitter Card 元標籤
            ->twitter(
                card: TwitterCard::SummaryWithLargeImage,
            );
    });

    // 訪問不存在的頁面時的 Head 設定
    Head::errors(function (ErrorPages $errors): void {
        $errors->status(404, fn (HeadBuilder $head): HeadBuilder => $head
            ->title('Page Not Found')
            ->description('找不到該頁面。')
        );
    });
}

什麼是 Canonical URL(標準網址 / 規範網址)?

當同一個網頁有多個不同網址可以存取時,Canonical URL(標準網址 / 規範網址)可以告訴搜尋引擎(如 Google)哪一個網址才是最主要、最具權威性的原始版本。它的核心目的在於解決重複內容(Duplicate Content)問題,並將外部連結權重(Page Rank)集中在單一網址上。

例如下列網址皆指向同一頁面:

  • https://example.com
  • https://www.example.com
  • http://example.com

你可以使用 Canonical URL 告訴 Google 第一個才是主要的網址。

完成預設的設定後,我們要在 app.blade.php 中加上 @head 的 Blade 語法:

<html>
<head>
    <meta charset="utf-8">
    <!-- [!code highlight:1] -->
    @head

    @viteReactRefresh
    @vite(['resources/css/app.css', 'resources/js/app.ts'])
    <x-inertia::head />
</head>
<body>
    <x-inertia::app />
</body>
</html>

如果你的 Inertia.js 有開啟 Server Side Rendering,可以在 createInertiaApp() 中開啟 serverHead:

createInertiaApp({
    // ...
    serverHead: true,
});

完成上述的設定,你就可以在頁面上看到生成的元標籤:

<title>note.docfunc</title>
<meta name="description" content="...">
<link rel="canonical" href="https://note.docfunc.com/">
<meta property="og:type" content="website">
<meta property="og:site_name" content="note.docfunc">
<meta property="og:title" content="note.docfunc">
<meta property="og:description" content="...">
<meta name="twitter:card" content="summary_large_image">
<meta name="twitter:title" content="note.docfunc">
<meta name="twitter:description" content="...">

在特定頁面覆寫標籤

當我們想在不同的頁面使用不一樣的元標籤,你可以在 Controller 中覆寫預設的 Head 設定:

class ShowNoteController extends Controller
{
    // ...

    public function __invoke(string $category, string $note): Response
    {
        // ...

        Head::title($found['title'])
            ->description($description)
            ->og(
                type: OgType::Article,
                title: $found['title'],
                description: $description,
            );

        Head::ogImage(route('notes.note.og', ['category' => $category, 'note' => $note]));

        // ...
    }
}

有了 Head 套件,我們就不用再為了網頁的 SEO(Search Engine Optimization)去自己手搓元標籤,實在是相當的方便!✌️

參考資料

Allen
written by
Allen

持續努力中的後端打工仔,在下班後喜歡研究各種不同的技術。稍微擅長 PHP,並偶爾涉獵前端開發。個性就像動態語言般隨興,但渴望做事能像囉嗦的靜態語言那樣嚴謹。

則留言
顯示更多留言
新增留言
訪客 2026 年 11 月 01 日