Use Cases

SEO: Claude Code 활용 가이드

seo: Claude Code 활용. 실용적인 팁과 코드 예시를 포함합니다.

サイトマップ自動생성でSEO対策を효율화

サイトマップはGoogleなどの검색エンジンにサイト構造を伝える重要な파일です。페이지が増えるたびに手動で업데이트するのは現実的ではありません。Claude Code를 활용하면 빌드時に自動생성される仕組みを短시간で구축할 수 있습니다。

기본적인サイトマップ생성スクリプト

> XMLサイトマップを自動생성するスクリプト를 생성해줘。
> 全페이지のURLを収集し、lastmod・changefreq・priorityを설정して。
// scripts/generate-sitemap.ts
import { globby } from 'globby';
import { writeFileSync } from 'fs';

interface SitemapEntry {
  url: string;
  lastmod: string;
  changefreq: 'daily' | 'weekly' | 'monthly';
  priority: number;
}

async function generateSitemap() {
  const baseUrl = 'https://example.com';
  
  // 페이지파일を収集
  const pages = await globby([
    'src/pages/**/*.astro',
    'src/content/blog/**/*.mdx',
    '!src/pages/api/**',
    '!src/pages/404.astro',
  ]);

  const entries: SitemapEntry[] = pages.map(page => {
    const path = page
      .replace('src/pages/', '')
      .replace('src/content/blog/', 'blog/')
      .replace(/\.(astro|mdx)$/, '')
      .replace(/\/index$/, '/');

    return {
      url: `${baseUrl}/${path}`,
      lastmod: new Date().toISOString().split('T')[0],
      changefreq: path.includes('blog') ? 'weekly' : 'monthly',
      priority: path === '' ? 1.0 : path.includes('blog') ? 0.7 : 0.8,
    };
  });

  const xml = buildXml(entries);
  writeFileSync('public/sitemap.xml', xml);
  console.log(`✅ サイトマップ生成完了: ${entries.length}ページ`);
}

function buildXml(entries: SitemapEntry[]): string {
  return `<?xml version="1.0" encoding="UTF-8"?>
<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
${entries.map(e => `  <url>
    <loc>${e.url}</loc>
    <lastmod>${e.lastmod}</lastmod>
    <changefreq>${e.changefreq}</changefreq>
    <priority>${e.priority}</priority>
  </url>`).join('\n')}
</urlset>`;
}

generateSitemap();

動的ルートへの대응

ブ로그글처럼動的に생성される페이지も、콘텐츠디렉터리から自動的に収集할 수 있습니다。

// Astro프로젝트での통합例
import { getCollection } from 'astro:content';

export async function getStaticPaths() {
  const posts = await getCollection('blog');
  return posts.map(post => ({
    params: { slug: post.slug },
    props: { post },
  }));
}

// サイトマップ用にメタ情報を출력
async function collectBlogEntries(baseUrl: string): Promise<SitemapEntry[]> {
  const posts = await getCollection('blog');
  
  return posts
    .filter(post => !post.data.draft)
    .map(post => ({
      url: `${baseUrl}/blog/${post.slug}`,
      lastmod: post.data.pubDate.toISOString().split('T')[0],
      changefreq: 'weekly' as const,
      priority: 0.7,
    }));
}

サイトマップ인덱스の구현

大規模サイトでは、サイトマップを分割して인덱스파일で관리します。

function buildSitemapIndex(sitemaps: string[]): string {
  const baseUrl = 'https://example.com';
  return `<?xml version="1.0" encoding="UTF-8"?>
<sitemapindex xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
${sitemaps.map(name => `  <sitemap>
    <loc>${baseUrl}/${name}</loc>
    <lastmod>${new Date().toISOString().split('T')[0]}</lastmod>
  </sitemap>`).join('\n')}
</sitemapindex>`;
}

// 用途別にサイトマップを分割
const sitemapFiles = [
  'sitemap-pages.xml',
  'sitemap-blog.xml',
  'sitemap-categories.xml',
];
writeFileSync('public/sitemap.xml', buildSitemapIndex(sitemapFiles));

빌드파이프라인への組み込み

{
  "scripts": {
    "build": "astro build && tsx scripts/generate-sitemap.ts",
    "sitemap": "tsx scripts/generate-sitemap.ts",
    "postbuild": "tsx scripts/generate-sitemap.ts && tsx scripts/ping-search-engines.ts"
  }
}

robots.txtとの연동

> robots.txtにサイトマップのURL를 추가해줘。
User-agent: *
Allow: /

Sitemap: https://example.com/sitemap.xml

Google Search Consoleへの알림

// scripts/ping-search-engines.ts
async function pingSearchEngines(sitemapUrl: string) {
  const endpoints = [
    `https://www.google.com/ping?sitemap=${encodeURIComponent(sitemapUrl)}`,
    `https://www.bing.com/ping?sitemap=${encodeURIComponent(sitemapUrl)}`,
  ];

  for (const url of endpoints) {
    try {
      const res = await fetch(url);
      console.log(`Ping ${url}: ${res.status}`);
    } catch (error) {
      console.error(`Ping失敗: ${url}`, error);
    }
  }
}

pingSearchEngines('https://example.com/sitemap.xml');

정리

サイトマップの自動생성は、SEO対策の基本中の基本です。Claude Code를 활용하면 動的ルートの収集から빌드파이프라인への組み込みまで一気に구현할 수 있습니다。CI/CD파이프라인に組み込むことで、배포のたびに最新のサイトマップが自動的に생성されます。詳しい仕様はsitemaps.org를 참고하세요.

#Claude Code #sitemap #SEO #XML #automation