Django向けllms.txt

Djangoには複数の方法があります:Nginx経由で配信する静的ファイル、HttpResponseを返すシンプルなビュー、データベースモデルから生成する動的ビュー、または高トラフィックサイト向けのキャッシュ済みビューです。

最終更新:

オプション1:STATICFILES_DIRSを使用した静的ファイル

Djangoの staticfiles フレームワークはファイルをコピー元から STATICFILES_DIRS から STATIC_ROOT を実行するとき collectstatic。その後、Nginx を設定してファイルを直接配信できますが、URL が STATIC_URL プレフィックス(例: /static/llms.txt)配下となり、ルートには配置されません。

static/llms.txt, approach notes
# Django static file approach
#
# 1. Place llms.txt in one of your STATICFILES_DIRS:
#    myproject/
#    ├── static/
#    │   └── llms.txt   ← add this
#    └── myapp/
#
# 2. In settings.py, make sure STATICFILES_DIRS includes the static/ folder:
#    STATICFILES_DIRS = [BASE_DIR / "static"]
#
# 3. Run collectstatic to copy it to STATIC_ROOT:
#    python manage.py collectstatic
#
# NOTE: Django's staticfiles serve files under the STATIC_URL prefix (/static/ by default).
# This means the file will be at /static/llms.txt, NOT /llms.txt.
# Use the view approach below to serve at the root path /llms.txt.

/llms.txt で静的ファイルを配信するには、Nginx に alias デプロイメントセクションの下にあるNginxスニペットを参照してください。 STATIC_ROOT。以下のデプロイセクションにある Nginx スニペットを参照してください。

選択肢2: HttpResponseを使うカスタムビュー

最も簡潔な Django の方法は、正しい content_type。あらゆるデプロイ先で動作し、ファイルを正確に次の場所で配信します: /llms.txt.

myapp/views.py
# myapp/views.py
from django.http import HttpResponse

LLMS_TXT_CONTENT = """# My Site

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

## Documentation

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

## Product

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

## Optional

- [Changelog](https://mysite.com/changelog/): Release history.
- [GitHub](https://github.com/my-org/my-repo): Source code.
"""


def llms_txt(request):
    return HttpResponse(
        LLMS_TXT_CONTENT,
        content_type="text/plain; charset=utf-8",
        headers={
            "Cache-Control": "public, max-age=3600, stale-while-revalidate=86400",
        },
    )

ルートディレクトリに配置してください urls.py:

myproject/urls.py
# myproject/urls.py
from django.urls import path
from myapp.views import llms_txt

urlpatterns = [
    # Serve at /llms.txt (root path)
    path("llms.txt", llms_txt, name="llms-txt"),
    # ... your other URL patterns
]

path("llms.txt", ...) パターン(先頭にスラッシュなし)が URL /llms.txt。Django は照合前に先頭のスラッシュを取り除きます。

選択肢3:モデルから動的に生成

ドキュメントページをデータベースに保存しているサイトでは、クエリセットからファイルの内容を生成します。Django 組み込みの cache_page リクエストのたびにデータベースにアクセスするのを避けるためのデコレータ。

myapp/views.py, dynamic
# myapp/views.py
# Dynamic generation from database models
from django.http import HttpResponse
from django.views.decorators.cache import cache_page
from myapp.models import DocumentPage


# Cache for 1 hour, regenerated automatically when cache expires
@cache_page(60 * 60)
def llms_txt(request):
    docs = DocumentPage.objects.filter(
        published=True,
        include_in_llms=True,
    ).order_by("order").values("title", "slug", "summary")

    lines = ["# My Site", "", "> Documentation and API reference.", "", "## Documentation", ""]

    for doc in docs:
        url = f"https://mysite.com/docs/{doc['slug']}/"
        lines.append(f"- [{doc['title']}]({url}): {doc['summary']}")

    lines += [
        "",
        "## Optional",
        "",
        "- [Changelog](https://mysite.com/changelog/): Release history.",
    ]

    return HttpResponse(
        "\n".join(lines),
        content_type="text/plain; charset=utf-8",
    )

真偽値フィールド include_in_llms モデルに渡して、どのページをファイルに掲載するかを編集者が管理できるようにします。 バリデーター コンテンツ移行後は、書式設定の不具合を検出するため。

WSGI/ASGI デプロイ(Gunicorn、uWSGI、Nginx)

Djangoビューは一般的なすべてのデプロイ構成で動作します。ビュー自体は同期的で軽量なため、asyncは不要です。

nginx.conf, proxy to Gunicorn
# nginx.conf snippet, proxy to Gunicorn upstream
server {
    listen 80;
    server_name mysite.com;

    # Serve llms.txt directly from Gunicorn (Django view)
    location = /llms.txt {
        proxy_pass http://127.0.0.1:8000;
        proxy_set_header Host $host;
        proxy_cache_valid 200 1h;
        add_header Cache-Control "public, max-age=3600";
    }

    # Optionally serve a pre-built static copy faster:
    # location = /llms.txt {
    #     alias /srv/mysite/static_root/llms.txt;
    #     add_header Content-Type "text/plain; charset=utf-8";
    # }
}
  • Gunicorn、そのまま動作します。ビューは 200 を返し、 text/plain。特別な設定は不要です。
  • uWSGI、Gunicornと同様です。uWSGIの静的ファイル配信を使用する場合は、 /llms.txt ファイル内の STATIC_ROOTstatic-map = /llms.txt=/path/to/llms.txt.
  • ASGI (Daphne, Uvicorn)。このビューはそのままで互換性があります。Djangoは同期ビューを自動的にスレッドエグゼキューターでラップします。
  • Nginxキャッシュ、追加します proxy_cache_valid 200 1h Nginx の location ブロックでレスポンスをプロキシ層にキャッシュし、Django へのアクセスを クローラーのリクエストごとに避けるために.

検証

デプロイ後、ファイルが正しく配信されていることを確認します:

Verification
curl -I https://mysite.com/llms.txt
# Expected:
# HTTP/2 200
# content-type: text/plain; charset=utf-8

curl https://mysite.com/llms.txt | head -5
# Should print the first lines of your file

関連ガイド

ソース