---
slug: "django-csrf-elb-apache2-uwsgi"
title: "Django CSRFトークン認証に失敗する ELB -> Apache2 -> uwsgi"
description: "AWS ELB → Apache2 → uwsgi 構成の Django で CSRF トークン認証に失敗する問題と解決策。mod_wsgi から uwsgi に切り替えた際の HTTP/HTTPS スキーム判定の罠。"
url: "https://www.ytyng.com/blog/django-csrf-elb-apache2-uwsgi"
publish_date: "2016-09-16T03:24:38Z"
created: "2016-09-16T03:24:38Z"
updated: "2026-05-11T13:02:45.067Z"
categories: ["Django", "Linux"]
keywords: ""
featured_image_url: "https://media.ytyng.com/resize/20230812/0ebb2d9ba7534619bfe8dbcec84a6783.png.webp?width=768"
has_video: false
has_music: false
video_urls: []
music_urls: []
lang: "ja"
---

# Django CSRFトークン認証に失敗する ELB -> Apache2 -> uwsgi

<p>元々は<br>AWS ELB -&gt; Apache2 -&gt; mod_wsgi という構成だったが、<br>AWS ELB -&gt; Apache2 -&gt; uwsgi と、Djangoサーバを uwsgi に変えたら、<br><br>ログインフォームを送信する時など、django csrf 認証に失敗するようになった。<br><br><br>DEBUG = True で見てみると<br><br>アクセス禁止 (403)<br><br>CSRF検証に失敗したため、リクエストは中断されました。<br>Help<br><br>Reason given for failure:<br><br>    Referer checking failed - https://example.com.com/some-path/ does not match any trusted origins.<br>    <br><br>In general, this can occur when there is a genuine Cross Site Request Forgery, or when Django's CSRF mechanism has not been used correctly. For POST forms, you need to ensure:<br><br>    Your browser is accepting cookies.<br>    The view function passes a request to the template's render method.<br>    In the template, there is a {% csrf_token %} template tag inside each POST form that targets an internal URL.<br>    If you are not using CsrfViewMiddleware, then you must use csrf_protect on any views that use the csrf_token template tag, as well as those that accept the POST data.<br><br>You're seeing the help section of this page because you have DEBUG = True in your Django settings file. Change that to False, and only the initial error message will be displayed.<br><br>You can customize this page using the CSRF_FAILURE_VIEW setting.<br><br><br><br>ELB で HTTPS を受け、Apache には 80 でリクエスト、uwsgi は HTTP プロトコルをリッスンしている(uwsgiプロトコルではない)<br><br>Apacheの設定は<br><br>ProxyPass / http://127.0.0.1:8081/<br>ProxyPassReverse / http://127.0.0.1:8081/<br><br>Alias /static/ /var/django/xxxxx/staticfiles/<br>ProxyPass /static/ !<br><br>こんな感じ。<br><br>Django のコードを検索してみると<br><br>csrf.py<br><br>REASON_BAD_REFERER = "Referer checking failed - %s does not match any trusted origins."<br><br><br>こうなっていて、コードを読んで見ると CSRF_TRUSTED_ORIGINS にドメインを入れれば良いっぽい。<br><br>CSRF_TRUSTED_ORIGINS = [".example.com"] これで良い</p>
<p></p>
