Astro SEO: เพิ่ม Meta Tags และ Structured Data
#astro13 เม.ย. 2569
SEO ใน Astro
Astro เหมาะกับ SEO มากเพราะ render HTML บน server ทำให้ crawler เห็น content ได้ทันที
SEO Component
---
// src/components/SEO.astro
const {
title,
description,
image = '/og-default.jpg',
url = Astro.url.href,
type = 'website'
} = Astro.props;
const siteTitle = 'My Astro Site';
const fullTitle = title ? `${title} | ${siteTitle}` : siteTitle;
---
<title>{fullTitle}</title>
<meta name="description" content={description} />
<link rel="canonical" href={url} />
<!-- Open Graph -->
<meta property="og:type" content={type} />
<meta property="og:title" content={fullTitle} />
<meta property="og:description" content={description} />
<meta property="og:image" content={new URL(image, Astro.site)} />
<meta property="og:url" content={url} />
<!-- Twitter Card -->
<meta name="twitter:card" content="summary_large_image" />
<meta name="twitter:title" content={fullTitle} />
<meta name="twitter:description" content={description} />
<meta name="twitter:image" content={new URL(image, Astro.site)} />
ใช้ใน Layout
---
import SEO from '../components/SEO.astro';
const { title, description, image } = Astro.props;
---
<html lang="th">
<head>
<SEO title={title} description={description} image={image} />
</head>
<body>
<slot />
</body>
</html>
Structured Data (JSON-LD)
---
const article = {
'@context': 'https://schema.org',
'@type': 'Article',
headline: post.data.title,
description: post.data.description,
datePublished: post.data.pubDate.toISOString(),
author: {
'@type': 'Person',
name: post.data.author
}
};
---
<script type="application/ld+json" set:html={JSON.stringify(article)} />
Sitemap
npx astro add sitemap
// astro.config.mjs
import sitemap from '@astrojs/sitemap';
export default defineConfig({
site: 'https://mysite.com',
integrations: [
sitemap({
filter: (page) => !page.includes('/admin')
})
]
});
robots.txt
// public/robots.txt
User-agent: *
Allow: /
Disallow: /admin/
Sitemap: https://mysite.com/sitemap-index.xml
สรุป
Astro ให้ SEO ที่ดีมากโดย default เพราะ HTML ถูก render บน server ทำให้ crawler เห็น content ได้ทันที ไม่ต้องรอ JavaScript ครับ