Astro × Cloudflare Pages で Core Web Vitals と SEO を最適化する実践レシピ【実コード公開】

PurgeCSS インライン展開・エッジキャッシュヘッダ・WebP preload・301 URL正規化まで、本番サイトで実装した全設定

この記事でわかること(コピペで流用できる実コード付き)

  • astro-purgecss で削減した CSS をさらに <style> にインライン展開し、レンダリングブロックを解消する Astro インテグレーション
  • Cloudflare Pages の public/_headers で TTFB / 再訪表示を改善するキャッシュヘッダ設計
  • LCP 対象となるヒーロー画像の WebP 自動判定+rel="preload" fetchpriority="high" の実装
  • functions/_middleware.ts による www 統一+末尾スラッシュ 301 正規化(POST 保持・静的ファイル除外)

Astro と Cloudflare Pages の組み合わせはデフォルトでも高速ですが、実運用で Core Web Vitals(特に LCP / TTFB) と Search Console 上のインデックス正規化 まで詰めようとすると、いくつか追加で手を入れるべきポイントが出てきます。

この記事では、当サイト(www.diverstage.biz)の本番運用で実際に組み込んでいる 4 つの最適化レシピを、そのまま流用できる設定コード付きでまとめました。

全体像:4 つの最適化ポイントと狙い

対象領域 実装ファイル 狙い・効果
CSS レンダリングブロック解消 astro.config.mjs 未使用 CSS を PurgeCSS で削除したうえで HTML へインライン展開し、初回描画の外部 CSS 往復をゼロにする
エッジ/ブラウザキャッシュ最適化 public/_headers ハッシュ付きアセットは immutable、HTML は CDN-Cache-Control でエッジ配信し TTFB を短縮
LCP ヒーロー画像の先行読み込み BaseLayout.astro .webp の存在をビルド時に自動判定し、<link rel="preload" as="image" fetchpriority="high"> を出力
URL 正規化(www・末尾スラッシュ) functions/_middleware.ts apex ドメインと末尾スラッシュなし URL を 1 ホップで 301 正規化し、Search Console の重複評価を防止

1. PurgeCSS 後の CSS を HTML にインライン展開する

Bulma などの CSS フレームワークを併用している場合、astro-purgecss を使うことで未使用ルールを大幅に削れます。さらにビルド完了フック(astro:build:done)で外部 CSS の <link rel="stylesheet"> を <style> へインライン展開すると、初回表示時の外部 CSS ダウンロード待ち(レンダリングブロック)を完全に排除できます。

astro.config.mjs の実装例

import fs from 'node:fs/promises';
import path from 'node:path';
import { fileURLToPath } from 'node:url';
import { defineConfig } from 'astro/config';
import purgecss from 'astro-purgecss';

function inlinePurgedStylesheets() {
  return {
    name: 'inline-purged-stylesheets',
    hooks: {
      'astro:build:done': async ({ dir }) => {
        const outDir = fileURLToPath(dir);
        const cssCache = new Map();

        async function collectHtmlFiles(currentDir) {
          const entries = await fs.readdir(currentDir, { withFileTypes: true });
          const files = [];
          for (const entry of entries) {
            const fullPath = path.join(currentDir, entry.name);
            if (entry.isDirectory()) {
              files.push(...(await collectHtmlFiles(fullPath)));
            } else if (entry.isFile() && entry.name.endsWith('.html')) {
              files.push(fullPath);
            }
          }
          return files;
        }

        const htmlFiles = await collectHtmlFiles(outDir);
        const linkRegex = /<link\s+rel="stylesheet"\s+href="(\/_astro\/[^"]+\.css)"(?:\s*\/?)>/g;

        for (const htmlFile of htmlFiles) {
          const html = await fs.readFile(htmlFile, 'utf8');
          const matches = [...html.matchAll(linkRegex)];
          if (matches.length === 0) continue;

          let updated = html;
          for (const [fullTag, href] of matches) {
            let css = cssCache.get(href);
            if (css === undefined) {
              const cssPath = path.join(outDir, href.replace(/^\/+/, ''));
              try {
                css = await fs.readFile(cssPath, 'utf8');
                cssCache.set(href, css);
              } catch {
                css = null;
                cssCache.set(href, null);
              }
            }
            if (css !== null) {
              const safeCss = css.replace(/<\/style>/gi, '<\\/style>');
              updated = updated.replace(fullTag, `<style>${safeCss}</style>`);
            }
          }

          if (updated !== html) {
            await fs.writeFile(htmlFile, updated, 'utf8');
          }
        }
      },
    },
  };
}

export default defineConfig({
  site: 'https://www.diverstage.biz/',
  trailingSlash: 'always',
  integrations: [
    purgecss({
      safelist: {
        // JavaScript から動的に付与するクラスは必ず safelist に登録する
        standard: ['is-dark', 'is-active', 'is-copied', 'is-scrolled', 'is-danger', 'is-loading'],
        deep: [/^is-dark/, /^search-/],
      },
    }),
    // purgecss の後に実行するのがポイント
    inlinePurgedStylesheets(),
  ],
});

運用上の注意点:integrations の並び順で purgecss() の後に inlinePurgedStylesheets() を配置してください。また、ダークモード切替やボタンの状態変化など JS から動的に付与するクラス は PurgeCSS に削除されないよう safelist へ明示しておきます。


2. Cloudflare Pages の _headers でキャッシュ戦略を最適化する

Astro のビルド成果物はファイル名にハッシュが付くため、アセット種別ごとにキャッシュ期間を明確に分けると、エッジ配信(TTFB)とリピート訪問時の表示速度が大きく改善します。

public/_headers の実装例

# Immutable hashed Astro build assets
/_astro/*
  Cache-Control: public, max-age=31536000, immutable

# Static media assets
/uploads/*
  Cache-Control: public, max-age=2592000, stale-while-revalidate=86400

/img/*
  Cache-Control: public, max-age=2592000, stale-while-revalidate=86400

# API endpoints should never be cached
/api/*
  Cache-Control: no-store

# Static HTML pages: revalidate in browser, cache at CDN edge
/*
  Cache-Control: public, max-age=0, must-revalidate
  CDN-Cache-Control: public, max-age=3600

HTML(/*)に Cache-Control: public, max-age=0, must-revalidate と CDN-Cache-Control: public, max-age=3600 を併用することで、ブラウザには常に最新の更新確認をさせつつ、Cloudflare エッジから高速に応答させることができます。


3. LCP ヒーロー画像の WebP 自動判定と fetchpriority="high"

ファーストビューのヒーロー画像は多くのページで LCP(Largest Contentful Paint)要素になります。<picture> タグで .webp と .jpg/.png を出し分けている場合、<head> 内の <link rel="preload"> も .webp の有無に合わせて出力しないと、ブラウザが不要な JPEG を先行取得してしまいます。

BaseLayout.astro の実装例

---
import fs from 'node:fs';
import path from 'node:path';
import { getWebpPath } from '../utils/categories';

const { preloadImage } = Astro.props;

let resolvedPreloadHref: string | undefined;
let resolvedPreloadType: string | undefined;

if (preloadImage) {
  const webpCandidate = getWebpPath(preloadImage);
  const hasWebp =
    webpCandidate !== preloadImage &&
    fs.existsSync(path.join(process.cwd(), 'public', webpCandidate.replace(/^\/+/, '')));

  if (hasWebp) {
    resolvedPreloadHref = webpCandidate;
    resolvedPreloadType = 'image/webp';
  } else {
    resolvedPreloadHref = preloadImage;
  }
}
---

<head>
  {
    resolvedPreloadHref && (
      <link
        rel="preload"
        as="image"
        href={resolvedPreloadHref}
        type={resolvedPreloadType}
        fetchpriority="high"
      />
    )
  }
</head>

ビルド時に public/ 配下の .webp の存在をチェックして type="image/webp" 付きで preload することで、HTML パース開始直後から最優先で WebP の取得が走ります。


4. functions/_middleware.ts で www と末尾スラッシュを 1 ホップ 301 正規化

Search Console でドメインプロパティを運用していると、<link rel="canonical"> を設定していても https://example.com/path(www なし・スラッシュなし) と https://www.example.com/path/(www あり・スラッシュあり) の両方が 200 OK で応答し、評価が分散してしまうケースが少なくありません。

Cloudflare Pages Functions の _middleware.ts を使えば、静的ファイルや API を壊さずに 1 ホップで正規 URL へ 301 リダイレクト できます。

functions/_middleware.ts の実装例

const CANONICAL_HOST = 'www.diverstage.biz';
const APEX_HOST = 'diverstage.biz';

interface MiddlewareContext {
  request: Request;
  next: () => Promise<Response>;
}

function shouldAddTrailingSlash(pathname: string): boolean {
  if (!pathname || pathname === '/' || pathname.endsWith('/')) {
    return false;
  }

  // API・ビルド成果物・隠しパスは対象外
  if (
    pathname === '/api' ||
    pathname.startsWith('/api/') ||
    pathname.startsWith('/_astro/') ||
    pathname.startsWith('/.well-known/')
  ) {
    return false;
  }

  // 拡張子付き静的ファイル(.xml, .txt, .json, 画像等)は対象外
  const lastSegment = pathname.split('/').pop() ?? '';
  if (lastSegment.includes('.')) {
    return false;
  }

  return true;
}

export const onRequest = async (context: MiddlewareContext): Promise<Response> => {
  const { request, next } = context;
  const url = new URL(request.url);
  const isSafeMethod = request.method === 'GET' || request.method === 'HEAD';

  let needsRedirect = false;

  // 1. apex -> www 正規化
  if (url.hostname === APEX_HOST) {
    url.hostname = CANONICAL_HOST;
    url.protocol = 'https:';
    needsRedirect = true;
  }

  // 2. HTML ページ相当の末尾スラッシュ正規化(Astro trailingSlash: 'always' と一致)
  if (isSafeMethod && shouldAddTrailingSlash(url.pathname)) {
    url.pathname = `${url.pathname}/`;
    needsRedirect = true;
  }

  if (needsRedirect) {
    // GET/HEAD は 301、POST 等はボディを保持する 308
    return Response.redirect(url.toString(), isSafeMethod ? 301 : 308);
  }

  return next();
};

設計上のポイント:

  • https://diverstage.biz/categories/about のようなアクセスでも、ホスト名と末尾スラッシュを同時に書き換えるため 2 回リダイレクトせず 1 ホップで https://www.diverstage.biz/categories/about/ に着地します。
  • POST /api/contact のような API 呼び出しは末尾スラッシュを付けず、ホスト名違いのときも 308 を返すことでリクエストボディが失われません。
  • Astro 側の trailingSlash: 'always'(dist/<slug>/index.html 出力)と揃えることで、Cloudflare Pages の静的アセット配信とのリダイレクトループを防げます。

まとめ:導入チェックリスト

Astro × Cloudflare Pages サイトを本番公開する際は、次の 4 点をセットでチェックしておくとパフォーマンスと SEO の取りこぼしを防げます。

  1. astro-purgecss の safelist に動的クラスを登録したうえで、ビルド後に CSS をインライン化しているか
  2. public/_headers で /_astro/*(immutable)と HTML(CDN-Cache-Control)のキャッシュ設計を分けているか
  3. ファーストビューの LCP 画像が .webp かつ fetchpriority="high" で先行読み込みされているか
  4. www の有無・末尾スラッシュの有無が canonical / サイトマップ / 301 リダイレクトのすべてで統一されているか

Diverstage では、既存 WordPress サイトの高速化や Astro / Cloudflare Pages へのリプレイス、Core Web Vitals 改善のご相談を承っています。「今のサイトの表示速度を診断してほしい」「移行の費用感を知りたい」といった段階でも、下記よりお気軽にご相談ください。