Laravel 的 llms.txt

Laravel 的 public/ 目录就是 Web 根目录,无需配置。若要动态生成,请在 routes/web.php 中添加路由,或创建使用 Laravel Cache facade 的专用控制器。

最近更新:

public/ 中的选项 1:静态文件

Laravel 的 public/ 目录是由 nginx 或 Apache 提供服务的文档根目录。放在其中的任何文件都可通过对应网址路径访问,无需路由配置。这是最简单的方法,完全不需要修改代码。

public/llms.txt, directory structure
# Laravel static file approach
#
# Laravel's public/ directory is the web root (served by nginx/Apache).
# Drop your file here and it is immediately available at /llms.txt.
#
# Project structure:
# your-laravel-app/
# ├── public/
# │   ├── index.php
# │   └── llms.txt   ← add this
# ├── routes/
# └── app/
#
# No code change needed. Works on Forge, Vapor, Heroku, and bare VPS.

此方法适用于所有 Laravel 部署目标: Laravel Forge, Laravel Vapor, Heroku, Railway以及裸 VPS 服务器。Web 服务器(nginx/Apache)直接提供该文件,无需经过 PHP,因此速度也更快。

选项 2:routes/web.php 中的路由

当你希望以程序方式生成内容,或从代码而不是 文件来管理它时,请在 routes/web.php:

routes/web.php
<?php
// routes/web.php, serve llms.txt via a named route

use Illuminate\Support\Facades\Route;

Route::get('/llms.txt', function () {
    $content = <<<'LLMS'
# Your Site

> One-sentence description of what your site or product does.

## Documentation

- [Getting Started](https://yoursite.com/docs/start): Install and configure in minutes.
- [API Reference](https://yoursite.com/docs/api): Full endpoint catalog with examples.

## Product

- [Overview](https://yoursite.com/product): Core features and capabilities.
- [Pricing](https://yoursite.com/pricing): Plans and billing details.

## Optional

- [Changelog](https://yoursite.com/changelog): Release history.
LLMS;

    return response($content, 200)
        ->header('Content-Type', 'text/plain; charset=utf-8')
        ->header('Cache-Control', 'public, max-age=3600, stale-while-revalidate=86400');
})->name('llms-txt');

使用 PHP 的 heredoc 语法(<<<'LLMS') 将内容以内联方式写入 而不必担心转义。单引号 heredoc 标记意味着不会进行变量 插值,内容会被当作字面字符串处理。

选项 3:带缓存的控制器

对于从数据库动态生成的内容,例如拉取已发布的 文档页面,请使用专用的可调用控制器,并配合 Cache::remember() ,以避免每次请求都查询数据库:

app/Http/Controllers/LlmsTxtController.php
<?php
// app/Http/Controllers/LlmsTxtController.php

namespace App\Http\Controllers;

use Illuminate\Http\Response;
use Illuminate\Support\Facades\Cache;

class LlmsTxtController extends Controller
{
    public function __invoke(): Response
    {
        // Cache for 1 hour, regenerates automatically when expired
        $content = Cache::remember('llms_txt', 3600, function () {
            return $this->buildContent();
        });

        return response($content, 200)
            ->header('Content-Type', 'text/plain; charset=utf-8')
            ->header('Cache-Control', 'public, max-age=3600, stale-while-revalidate=86400');
    }

    private function buildContent(): string
    {
        // You can query your database here:
        // $docs = \App\Models\Doc::published()->get();
        // $links = $docs->map(fn($d) => "- [{$d->title}](https://yoursite.com/docs/{$d->slug}): {$d->summary}")->join("\n");

        return <<<'LLMS'
# Your Site

> One-sentence description of your product.

## Documentation

- [Getting Started](https://yoursite.com/docs/start): Install and configure in minutes.
- [API Reference](https://yoursite.com/docs/api): Full endpoint catalog with examples.

## Optional

- [Changelog](https://yoursite.com/changelog): Release history.
LLMS;
    }
}
routes/web.php, controller registration
<?php
// routes/web.php, register the controller route

use App\Http\Controllers\LlmsTxtController;
use Illuminate\Support\Facades\Route;

Route::get('/llms.txt', LlmsTxtController::class)->name('llms-txt');

Cache::remember() 会将结果存储在你配置的缓存驱动中(Redis、Memcached、数据库或文件)。缓存会在 3600 秒后自动重新生成。若要在内容更新后立即使缓存失效,请调用 Cache::forget('llms_txt') 的观察器中,或者在部署钩子之后。

用于复用的响应宏

如果你提供多个纯文本文件,或者希望在应用中保持一致的模式, 请注册一个 plaintext() 响应宏,位于 AppServiceProvider:

app/Providers/AppServiceProvider.php
<?php
// app/Providers/AppServiceProvider.php, response macro for reusability

namespace App\Providers;

use Illuminate\Support\Facades\Response;
use Illuminate\Support\ServiceProvider;

class AppServiceProvider extends ServiceProvider
{
    public function boot(): void
    {
        // Register a plaintext() macro for serving text/plain responses
        Response::macro('plaintext', function (string $content, int $maxAge = 3600) {
            return Response::make($content, 200, [
                'Content-Type'  => 'text/plain; charset=utf-8',
                'Cache-Control' => "public, max-age={$maxAge}, stale-while-revalidate=86400",
            ]);
        });
    }
}

// Usage in a route or controller:
// return response()->plaintext($content);

然后,这个宏就可以通过以下方式在你的应用中任意位置使用: response()->plaintext($content),同时保持 Content-TypeCache-Control 响应头保持一致。

验证

部署后,确认文件已正确提供:

Verification
curl -I https://yoursite.com/llms.txt
# Expected:
# HTTP/2 200
# content-type: text/plain; charset=utf-8
# cache-control: public, max-age=3600

curl https://yoursite.com/llms.txt | head -5
# Should print: # Your Site

然后将 URL 粘贴到 llms.txt 验证器 以进行完整的规范合规性检查。

发布前检查清单

  • 文件提供于 /llms.txt200 OK.
  • Content-Type: text/plain; charset=utf-8 已设置。
  • Cache-Control 标头存在。
  • 响应为纯文本,不含 HTML,也不含 Blade 输出。
  • 顶部只能有一个 H1 标题。
  • 紧接在 H1 后的引用块摘要。
  • 所有 URL 都是绝对的(https://).
  • 未对该内容应用认证中间件 /llms.txt 路由。
  • 验证器未返回错误: llmtxt.info/validator/

相关指南

来源