Astro 站点配置与 SEO
SEO 基本三件套
搜索引擎和社交分享最看重三样:标题、描述、社交卡片图,在布局(Astro 布局)里统一输出即可。
---
const { title, description = '我的 Astro 站点' } = Astro.props;
const ogImage = '/images/og.png';
---
<meta name="description" content={description} />
<meta property="og:title" content={title} />
<meta property="og:description" content={description} />
<meta property="og:image" content={ogImage} />
规范链接 canonical
告诉搜索引擎「这个页面的权威地址」,避免重复内容问题。
<!-- Astro.url 是当前页面网址,Astro.site 是配置的站点域名,合并成绝对地址 -->
<link rel="canonical" href={new URL(Astro.url.pathname, Astro.site)} />
Astro.site 来自 astro.config.mjs 里的 site 字段(Astro 环境变量与配置)。
站点地图 sitemap
安装官方 sitemap 集成,构建时会自动生成 sitemap-index.xml。
npx astro add sitemap
它会读取 site 配置,把全部页面列进去,方便搜索引擎收录。
RSS 订阅
内容站通常提供 RSS,让读者用阅读器订阅,安装 @astrojs/rss 后在端点(Astro 服务端端点)里生成。
// src/pages/rss.xml.ts
import rss from '@astrojs/rss';
import { getCollection } from 'astro:content';
export async function GET(context) {
const posts = await getCollection('blog');
// rss() 生成 RSS XML;context.site 来自配置里的 site 字段
return rss({
title: '我的站点',
link: context.site,
items: posts.map((p) => ({
title: p.data.title,
link: `/blog/${p.id}`,
})),
});
}
robots.txt
在 public/ 里放 robots.txt,指引爬虫。
User-agent: *
Allow: /
Sitemap: https://example.com/sitemap-index.xml
结构化数据
对文章、教程加 JSON-LD,能帮助搜索引擎理解内容类型,有机会获得富媒体展示。
其中 set:html 用于把字符串原样注入 HTML(用法见 Astro 组件模板语法)。
<script type="application/ld+json" set:html={JSON.stringify({
'@context': 'https://schema.org',
'@type': 'Article',
headline: post.data.title,
})} />