Fix CSRF behind Nginx by configuring trusted origins via environment.

Reads CSRF_TRUSTED_ORIGINS and USE_HTTPS from env so admin login works correctly behind HTTPS reverse proxies.

Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
Pirmin Hinderling (fedora)
2026-07-07 19:49:41 +02:00
parent db3558872e
commit ae71704cc5
3 changed files with 23 additions and 7 deletions
+7
View File
@@ -1,3 +1,10 @@
# Django (Produktion)
DJANGO_DEBUG=False
DJANGO_SECRET_KEY=change-me
ALLOWED_HOSTS=faktenkompass.example.com
CSRF_TRUSTED_ORIGINS=https://faktenkompass.example.com
USE_HTTPS=True
# OpenAI API-Schlüssel für den Fakten-Assistenten im Admin
OPENAI_API_KEY=sk-...
+4 -7
View File
@@ -93,6 +93,8 @@ DJANGO_SETTINGS_MODULE=faktenkompass.settings
DJANGO_DEBUG=False
DJANGO_SECRET_KEY=lange-zufaellige-zeichenkette
ALLOWED_HOSTS=faktenkompass.example.com,www.faktenkompass.example.com
CSRF_TRUSTED_ORIGINS=https://faktenkompass.example.com,https://www.faktenkompass.example.com
USE_HTTPS=True
DB_ENGINE=django.db.backends.postgresql
DB_NAME=faktenkompass
@@ -104,14 +106,9 @@ DB_PORT=5432
OPENAI_API_KEY=sk-...
```
Optional in `faktenkompass/settings.py` für HTTPS hinter Nginx ergänzen:
`CSRF_TRUSTED_ORIGINS` muss die **exakte URL** sein, mit der Sie die Seite aufrufen (Schema + Domain, ohne Pfad). Bei HTTP statt HTTPS z.B. `http://192.168.178.10` setzen und `USE_HTTPS=False`.
```python
SECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROTO', 'https')
CSRF_TRUSTED_ORIGINS = ['https://faktenkompass.example.com']
```
`SECRET_KEY`, `DEBUG` und `ALLOWED_HOSTS` sollten in der Produktion aus Umgebungsvariablen gelesen werden.
`USE_HTTPS=True` aktiviert Proxy-Header und sichere Cookies hinter Nginx mit HTTPS.
### 2. Deployment vorbereiten
+12
View File
@@ -35,6 +35,18 @@ ALLOWED_HOSTS = [
if host.strip()
]
CSRF_TRUSTED_ORIGINS = [
origin.strip()
for origin in os.environ.get('CSRF_TRUSTED_ORIGINS', '').split(',')
if origin.strip()
]
USE_HTTPS = os.environ.get('USE_HTTPS', '').lower() in ('true', '1', 'yes')
if USE_HTTPS:
SECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROTO', 'https')
CSRF_COOKIE_SECURE = True
SESSION_COOKIE_SECURE = True
# Application definition