Google AdSense を利用する時には、ads.txt をドメイン直下(/ads.txt)で公開する必要があります。
Django でサイトを構築していると、次のようなことで迷うことも多いです。
・ads.txt はどこに置けばいい?
・static 配下ではダメ?
・どうやって /ads.txt に対応させる?
この記事では、現在の Django 構成をできるだけ変えずに、ads.txt をルートパスで配信する方法を解説します。
Google AdSense の ads.txt をルートパスで配信する方法
既存の構成を崩さずに、**Viewで返す方法がシンプルです。
1. ads.txt ファイルを作成する
まずは、Google AdSense が提供する情報をそのまま保存します。
今回はローカルプロジェクト直下にファイルを置きました。
project_root/
├── ads.txt
├── manage.py
├── config/
└── core/ads.txtの内容は、AdSense が発行したコードを入力しておきます。
google.com, pub-XXXXXXXXXXXXXX, DIRECT, XXXXXXXXXXX2. ads.txt を返すビューを作成する
Django のビューで ads.txt を読み込み、text/plain として返すようにします。
core/views.py に以下を追加。
# core/views.py
from django.http import HttpResponse, Http404
from django.conf import settings
def ads_txt(request):
file_path = settings.BASE_DIR / "ads.txt"
if not file_path.exists():
raise Http404("ads.txt not found")
content = file_path.read_text(encoding="utf-8")
response = HttpResponse(content, content_type="text/plain")
# 軽いキャッシュ(任意)
response["Cache-Control"] = "public, max-age=86400"
return responseポイントは、以下の通り。
- ファイルが存在しなければ 404 を返す
text/plainを明示して Google のチェックを通す- プロジェクト内の
ads.txtをそのまま読み込む
3. URL を設定する
core/urls.py にルートパスで ads.txt を返す URL を追加します。
from django.urls import path
from core.views import ads_txt
urlpatterns = [
path("ads.txt", ads_txt),
]これで、ブラウザで以下へアクセスすると内容が表示されます。
4. 動作確認
ブラウザで確認する場合には、次のURLを開きましょう。
https://example.com/ads.txtcurlで確認する場合は、次のコマンドです。
curl -i https://example.com/ads.txt
# 200 OK
# Content-Type: text/plain
# 内容ads.txtについておさらい
ads.txt とは?
ads.txt(Authorized Digital Sellers)は、「このサイトの広告枠を販売してよい広告事業者を宣言するファイル」です。
これにより、次のことが行われます。
・広告詐欺の防止
・広告主の信頼性向上
・収益保護
AdSense を利用する場合、必須の設定です。
ads.txt の基本ルール
ads.txt は必ず ドメイン直下 に置く必要があります。
- OKな例
- NGな例
- /static/ads.txt
- /media/ads.txt
- /app/ads.txt
AdSense は /ads.txt しか見に行きません。
ads.txt の中身
AdSense の場合は基本これだけです。
google.com, pub-xxxxxxxxxxxxxxxx, DIRECT, xxxxxxxxxxxxxxxまとめ
Django で AdSense の ads.txt をルート提供するには、次の手順です。
- ads.txt をプロジェクト内に作成
- 読み込んで返すビューを書く
ads.txtという URL を追加する


コメント