Google AdSense を導入すると、サイトのルート直下(https://example.com/ads.txt)に
ads.txt ファイルを配置するように求められます。
静的ファイルではなく Django を使っている場合、
通常の STATIC_ROOT ではルートパスにファイルを置けません。
そこで今回は、Django で ads.txt をルート配信する方法をまとめました。
【Django】Google AdSense の ads.txt をルートパスで配信する方法
手順 1:ads.txt ファイルを作成する
まずは、Google AdSense が提供する情報をそのまま保存します。
今回はローカルプロジェクト直下にファイルを置きました。
/Users/username/Project/ads.txtads.txtの内容は、AdSense が発行したコードです。
google.com, pub-XXXXXXXXXXXXXX, DIRECT, XXXXXXXXXXX手順 2:ads.txt を返すビューを作成する
Django のビューで ads.txt を読み込み、text/plain として返すようにします。
core/views.py に以下を追加。
from django.http import HttpResponse, Http404
from pathlib import Path
def ads_txt(request):
file_path = Path(__file__).resolve().parent.parent / "ads.txt"
if not file_path.exists():
raise Http404("ads.txt not found")
content = file_path.read_text(encoding="utf-8")
return HttpResponse(content, content_type="text/plain; charset=utf-8")ポイントは、以下の通り。
- ファイルが存在しなければ 404 を返す
text/plainを明示して Google のチェックを通す- プロジェクト内の
ads.txtをそのまま読み込む
手順 3:URL を設定する
core/urls.py にルートパスで ads.txt を返す URL を追加します。
from django.urls import path
from . import views
urlpatterns = [
path("ads.txt", views.ads_txt, name="ads_txt"),
]これで、ブラウザで以下へアクセスすると内容が表示されます。
https://example.com/ads.txtこれでGoogle のクローラーも正しく認識してくれます。
■ まとめ
Django で AdSense の ads.txt をルート提供するには、次の手順です。
- ads.txt をプロジェクト内に作成
- 読み込んで返すビューを書く
ads.txtという URL を追加する
コメント