<!-- Generated from zh/llms-txt-astro/index.html. The canonical document is the HTML page. -->

- [ 首页 ](/zh/) 
/
- [ 如何创建 ](/zh/how-to-create/) 
/
- Astro 指南            
# 在 Astro 中使用 `llms.txt`

两种方法：将文件放入 public/ 以立即静态部署，或使用 TypeScript 端点根据内容集合动态生成。

最近更新: 2026年10月29日

本页内容

- [ 方法 1：public/ 中的静态文件 ](#approach-1)
- [ 方案 2：使用 getCollection() 的 TypeScript 端点 ](#approach-2)
- [ 添加 llms-full.txt ](#llms-full)
- [ Starlight 网站：starlight-llms-txt ](#starlight)
- [ 构建后验证 ](#verify)
- [ 该选择哪种方式 ](#which)               
示例

本网站运行于 Astro

llmtxt.info 本身使用 Astro 构建并托管于 Cloudflare Pages。以下方法正是 我们用来提供自己的  /llms.txt .

## 方案 1，静态文件位于 `public/`

这是最简单的方案。在以下位置创建纯文本文件： `public/llms.txt` 放在项目根目录中。 Astro
会将整个 `public/` 将目录原样复制到 `dist/` 期间 `astro build`，因此该文件通过以下路径提供：
`/llms.txt` ，无需任何配置。
static approach, public/llms.txt    复制     

```
# Place the file at: public/llms.txt
# Astro copies everything in public/ to the output directory as-is.
# Result: served at https://yoursite.com/llms.txt, no code changes needed.

# After deploy, verify:
curl -I https://yoursite.com/llms.txt
# Expected: HTTP/2 200 | Content-Type: text/plain
```

**何时使用这个：** 您的内容不经常变化、您希望构建时零开销， 或者您手动维护该文件。它在
Cloudflare Pages、Vercel、Netlify 及任何其他 Astro 托管平台上的工作方式相同。

## 方案 2：使用以下功能的 TypeScript 端点： `getCollection()`

Astro 匹配双扩展名 `.txt.ts` 并将
`src/pages/llms.txt.ts` 作为一个 API 端点，响应地址为
`/llms.txt`. 在 SSG 模式（默认）下，Astro 会将其预渲染为静态 `dist/llms.txt` 在构建时生成，无运行时成本。
src/pages/llms.txt.ts    复制     

```
// src/pages/llms.txt.ts
// Astro treats src/pages/foo.ext.ts as a route for /foo.ext
// In SSG mode (default), it pre-renders to dist/llms.txt at build time.

import type { APIRoute } from 'astro';
import { getCollection } from 'astro:content';

export const GET: APIRoute = async () => {
// Replace 'docs' with your actual content collection name
const docs = await getCollection('docs');

const lines = [
'# My Site',
'',
'> One-sentence description of what this site is about.',
'',
'## Documentation',
'',
...docs
.filter((d) => !d.data.draft)
.sort((a, b) => (a.data.order ?? 999) - (b.data.order ?? 999))
.map((d) => `- [${d.data.title}](https://yoursite.com/${d.id}/): ${d.data.summary ?? ''}`.trimEnd()),
'',
'## Optional',
'',
'- [Changelog](https://yoursite.com/changelog/): version history.',
];

return new Response(lines.join('\n'), {
headers: { 'Content-Type': 'text/plain; charset=utf-8' },
});
};

```

该端点假定存在一个 `docs` 集合。自 Astro 6 起，所有内容集合都必须使用 Content Layer API：构建时集合在
`src/content.config.ts`（而不是 `src/content/config.ts`）中通过 loader
声明，例如：
src/content.config.ts    复制     

```
// src/content.config.ts
// Build-time collections are defined here, each with a loader (Content Layer API).
import { defineCollection } from 'astro:content';
import { glob } from 'astro/loaders';
import { z } from 'astro/zod';

const docs = defineCollection({
loader: glob({ base: './src/content/docs', pattern: '**/*.{md,mdx}' }),
schema: z.object({
title: z.string(),
summary: z.string().optional(),
order: z.number().optional(),
draft: z.boolean().optional(),
}),
});

export const collections = { docs };

```

要点：

- 替换 `'docs'` 替换为 `src/content.config.ts`. 
- 条目不再具有 `slug` 属性：请使用 `entry.id` 构建 URL。内置
`glob()` loader 生成的 ID 已经过 slug 化处理。 
- 映射前过滤掉草稿： `!d.data.draft`. 
- 每行的注释（`: short note`) 是可选项，但强烈推荐，它 能为 LLM
提供每个页面的上下文，而无需它们先抓取页面。 
- 始终设置 `Content-Type: text/plain; charset=utf-8` 设置在响应中。     
警告

SSR 输出模式

如果你使用  output: 'server'  在  astro.config.mjs ，
端点会在每次请求时运行。对于高流量部署，请添加
export const prerender = true;  在文件顶部添加它，以便即使在服务器模式下也强制静态预渲染。

## 添加 `llms-full.txt`

该 [llms-full.txt](/zh/llms-full-txt/) 配套文件会内联每个页面的完整正文， 适用于希望一次获取全部语料库的
RAG 流水线和 LLM 客户端。创建一个并行端点：
src/pages/llms-full.txt.ts    复制     

```
// src/pages/llms-full.txt.ts
// Generates the full-content companion file.
// Each entry gets its full Markdown body inlined, useful for RAG pipelines.

import type { APIRoute } from 'astro';
import { getCollection } from 'astro:content';

export const GET: APIRoute = async () => {
const docs = await getCollection('docs');
const sections: string[] = [];

for (const doc of docs.filter((d) => !d.data.draft)) {
sections.push(
`# ${doc.data.title}`,
'',
`URL: https://yoursite.com/${doc.id}/`,
'',
doc.body ?? '', // raw, uncompiled Markdown/MDX body (undefined if retainBody is false)
'',
'---',
'',
);
}

return new Response(sections.join('\n'), {
headers: { 'Content-Type': 'text/plain; charset=utf-8' },
});
};

```

`doc.body` 包含 Markdown 或 MDX 条目未经编译的原始正文，因此输出中不含 HTML 标签。当 loader
的
`retainBody` 选项设置为 `false` 时，它为 `undefined`，因此回退为空字符串。

## Starlight 网站：`starlight-llms-txt`

对于使用 Starlight 构建的文档，社区插件 [starlight-llms-txt](https://delucis.github.io/starlight-llms-txt/) 会根据网站内容生成 `llms.txt`、`llms-full.txt` 和 `llms-small.txt`。它维护在 Chris Swithinbank（`delucis`）的个人 GitHub 仓库中，而不是 `withastro` 组织中。0.12.0 版本（发布于 2026 年 9 月 15 日）声明的 peer 依赖为 `astro ^7.0.0` 和
`@astrojs/starlight >=0.41.0`。必须设置 `site` URL：
astro.config.mjs, Starlight plugin    复制     

```
// astro.config.mjs
import starlight from '@astrojs/starlight';
import { defineConfig } from 'astro/config';
import starlightLlmsTxt from 'starlight-llms-txt';

export default defineConfig({
site: 'https://example.com/', // required by the plugin
integrations: [
starlight({
title: 'My Docs',
plugins: [starlightLlmsTxt()],
}),
],
});

```

## 构建后验证
verify    复制     

```
# Build the project
npx astro build

# Check static output (works for both approaches in SSG mode)
cat dist/llms.txt

# Or start preview server and curl:
npx astro preview &
curl http://localhost:4321/llms.txt
curl http://localhost:4321/llms-full.txt
```

部署后，将线上 URL 粘贴到 [验证器](/zh/validator/)
以确认符合规范：恰好一个 H1、有效的链接语法 (`- [title](https://...)`），所有 URL
均为绝对地址，且没有空分节。

## 该选择哪种方式

- **静态 `public/llms.txt`**，最适合不经常更新的网站。 零开销，无需
TypeScript，适用于所有环境。 
- **TypeScript 端点 `src/pages/llms.txt.ts`**，最适合拥有大量自动生成页面的文档网站。每次构建时，文件都会自动保持同步，无需手动编辑。   
&rarr; [完整创建指南](/zh/how-to-create/) &middot;
[Next.js 指南](/zh/llms-txt-nextjs/) &middot;
[WordPress 指南](/zh/llms-txt-wordpress/)

## 来源

- [ llmstxt.org，社区提案 ](https://llmstxt.org/)
- [ Astro，内容集合 ](https://docs.astro.build/en/guides/content-collections/)
- [ Astro，内容集合 API 参考 ](https://docs.astro.build/en/reference/modules/astro-content/)
- [ Astro，升级到 v6 ](https://docs.astro.build/en/guides/upgrade-to/v6/)
- [ Astro，端点 ](https://docs.astro.build/en/guides/endpoints/)
- [ starlight-llms-txt 文档 ](https://delucis.github.io/starlight-llms-txt/)
- [ starlight-llms-txt 源代码（delucis/starlight-llms-txt） ](https://github.com/delucis/starlight-llms-txt)
