Common Nginx Error Log Pattern (Python / Django)
When upstream sockets, timeouts, body limits, or Docker DNS rules are misconfigured for Python / Django, Nginx typically records an entry matching the log line below inside /var/log/nginx/error.log:
2026/11/22 19:35:08 [error] 6120#6120: *341 client intended to send too large body: 14829102 bytes, client: 203.0.113.55, server: portal.example.com, request: "POST /admin/uploads/document/add/ HTTP/2.0", host: "portal.example.com"
Reverse Proxy Architecture & Header Forwarding for Python / Django
Gunicorn's official documentation explicitly warns against exposing Gunicorn directly to the public internet because synchronous Python WSGI workers are vulnerable to slow-client denial-of-service attacks. Placing Nginx in front of Gunicorn (on http://127.0.0.1:8000 or a Unix socket) buffers slow mobile uploads completely in Nginx before handing complete HTTP requests to Gunicorn workers, while serving Django's /static/ and /media/ files directly from disk.
Django 4.x and 5.x enforce strict HTTPS origin validation on every POST form submission (including Django Admin logins). If Nginx terminates SSL on port 443 and forwards plain HTTP to Gunicorn without setting SECURE_PROXY_SSL_HEADER = ("HTTP_X_FORWARDED_PROTO", "https") and CSRF_TRUSTED_ORIGINS in settings.py, users hit immediate HTTP 403 "CSRF verification failed: Origin checking failed" errors on login.
In addition, Django Admin and Django REST Framework file uploads routinely fail in production with HTTP 413 Request Entity Too Large because Nginx defaults client_max_body_size to just 1 MB. Raising client_max_body_size to 50M in Nginx while pairing alias blocks for /static/ (populated by collectstatic) and /media/ ensures smooth admin uploads, fast CSS/JS delivery, and zero Gunicorn worker starvation.
Finally, verify that Nginx passes the exact external Host header ($host) rather than $http_host with unexpected ports, and list your domain in Django's ALLOWED_HOSTS so Django never rejects proxied requests with DisallowedHost (HTTP 400).
Maintaining a rock-solid Django and Gunicorn production server behind Nginx requires keeping three configuration layers synchronized: Nginx client_max_body_size and proxy_read_timeout, Gunicorn worker count and --timeout flags, and Django settings.py security constants (ALLOWED_HOSTS, SECURE_PROXY_SSL_HEADER, CSRF_TRUSTED_ORIGINS, and SECURE_HSTS_SECONDS). Running python manage.py check --deploy alongside sudo nginx -t during CI/CD catches mismatched HTTPS flags, insecure cookie settings, and broken static alias paths before traffic ever reaches production.
Step-by-Step Nginx & Python / Django Deployment Guide
Apply the Nginx server block above alongside these upstream framework trust-proxy settings so HTTPS detection, real client IPs, and reload safety work reliably in production.
1Configure Proxy SSL and CSRF Trusted Origins in Django settings.py
project/settings.pyTell Django to trust Nginx's X-Forwarded-Proto header for HTTPS detection, allow your production domain in ALLOWED_HOSTS, and add the https:// origin to CSRF_TRUSTED_ORIGINS for Django 4/5 Admin and form POSTs.
project/settings.pypythonALLOWED_HOSTS = ['portal.example.com'] # Required behind Nginx TLS termination in Django 4.0+ / 5.x SECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROTO', 'https') USE_X_FORWARDED_HOST = True CSRF_TRUSTED_ORIGINS = [ 'https://portal.example.com', ] SESSION_COOKIE_SECURE = True CSRF_COOKIE_SECURE = True2Serve Django /static/ and /media/ Directly From Nginx
/etc/nginx/sites-available/portal.example.com.confAdd /static/ and /media/ location blocks inside your generated HTTPS server block so Nginx serves static files directly off disk with long cache headers instead of hitting Gunicorn.
/etc/nginx/sites-available/portal.example.com.confnginxlocation /static/ { alias /srv/django-app/staticfiles/; expires 30d; add_header Cache-Control "public, immutable"; } location /media/ { alias /srv/django-app/media/; expires 7d; }3Run Gunicorn Under systemd Bound to Localhost Port 8000
/etc/systemd/system/gunicorn.serviceLaunch Gunicorn with (2 * CPU cores + 1) workers bound to 127.0.0.1:8000 and keep its timeout aligned below Nginx's proxy_read_timeout.
/etc/systemd/system/gunicorn.serviceini[Service] User=www-data Group=www-data WorkingDirectory=/srv/django-app ExecStart=/srv/django-app/.venv/bin/gunicorn project.wsgi:application \ --workers 5 \ --timeout 110 \ --bind 127.0.0.1:8000 Restart=always4Collect Static Files and Reload Nginx Without Downtime
terminalRun collectstatic so Nginx has fresh admin and app assets on disk, verify file permissions for www-data, and test + reload Nginx.
terminalbashpython manage.py collectstatic --noinput sudo nginx -t && sudo systemctl reload nginx
Common Python / Django Nginx Reverse Proxy Pitfalls
Review these three production failure modes before reloading Nginx on staging or live servers.
Django 4/5 403 CSRF Verification Failed After Enabling Nginx HTTPS
Starting in Django 4.0, CSRF middleware compares the browser Origin header against CSRF_TRUSTED_ORIGINS on HTTPS requests. Forgetting CSRF_TRUSTED_ORIGINS = ["https://portal.example.com"] or SECURE_PROXY_SSL_HEADER locks admins out of /admin/ immediately after adding SSL.
Missing Trailing Slash in Nginx alias /srv/django-app/staticfiles/;
Unlike root, Nginx's alias directive replaces the matched location path literally. Writing location /static/ with alias /srv/django-app/staticfiles (missing trailing slash) causes Nginx to look up /srv/django-app/staticfilesadmin/css/base.css and return 404 for every static asset.
Gunicorn Worker Timeout Killing Requests Before Nginx Times Out
Gunicorn defaults to a 30-second worker timeout (--timeout 30). Even if you raise Nginx proxy_read_timeout to 120s, Gunicorn kills slow report views at 30 seconds and Nginx logs "upstream prematurely closed connection" (502). Keep Gunicorn --timeout synchronized with Nginx.
Complete Your Deployment With Matching Docker Compose & CORS Tools
Pair this Nginx reverse proxy block with healthcheck-gated Docker Compose orchestration and verified browser CORS headers:
Deploy FastAPI, PostgreSQL 16, and Nginx on a Linux VPS with Docker Compose using pg_isready healthchecks, 127.0.0.1 firewall safety, and zero-downtime reloads.
Fix Nginx reverse proxy CORS bugs for Docker APIs. Prevent duplicate Access-Control-Allow-Origin headers, add always on 4xx/5xx errors, and handle OPTIONS 204.
Frequently Asked Questions
- Should Nginx proxy to Gunicorn over 127.0.0.1:8000 or a Unix domain socket?
- Both perform excellently on a single VM. Using 127.0.0.1:8000 avoids Unix socket file-permission headaches between systemd users and translates identically into Docker Compose networks later.
- Why does Django Admin load with zero CSS styling behind Nginx?
- In production with DEBUG = False, Django stops serving static files itself. Run python manage.py collectstatic and ensure your Nginx /static/ location block points to STATIC_ROOT with a matching trailing slash and readable permissions for the nginx user.
- Why did my Django upload fail with 413 Request Entity Too Large?
- Nginx caps request bodies at 1 MB by default. Increase client_max_body_size (e.g., 50M) in your Nginx server block AND check Django's DATA_UPLOAD_MAX_MEMORY_SIZE if uploading large non-file form payloads.
- Is it safe to set SECURE_PROXY_SSL_HEADER in Django?
- Yes, provided Nginx ALWAYS overwrites X-Forwarded-Proto using proxy_set_header X-Forwarded-Proto $scheme; (never forwarding a client-supplied value blindly) and Gunicorn is unreachable except through Nginx.
Related Nginx Reverse Proxy Guides
Browse all 10 Nginx guides →Nginx Reverse Proxy Config for FastAPI + Uvicorn (SSL, Docs & Timeouts)
Build a hardened Nginx reverse proxy config for Python FastAPI and Uvicorn/Gunicorn on port 8000 with --proxy-headers, SSL, WebSockets, and long timeouts.
Nginx Reverse Proxy for Docker Compose Services (127.0.0.11 DNS Resolver)
Prevent 502 Bad Gateway and Nginx startup crashes in Docker Compose using resolver 127.0.0.11 and variable proxy_pass for dynamic container restarts.
Nginx Reverse Proxy Config for ASP.NET Core Kestrel (Forwarded Headers & SignalR)
Build a production Nginx reverse proxy for ASP.NET Core 8/9 Kestrel on port 5000 with UseForwardedHeaders, SignalR WebSockets, SSL, and large OAuth headers.
Nginx Multi-Service Subpath Routing Config (/api/, /auth/ & /ws/)
Route /api/, /auth/, and /ws/ microservices to separate backend ports under one Nginx HTTPS domain. Master trailing-slash prefix stripping and prevent 404s.