Nginx Reverse Proxy Builder · Python / Django

Nginx Reverse Proxy Config for Django + Gunicorn (SSL, Static & CSRF)

Generate an Nginx reverse proxy server block for Python / Django with URL prefix rewrite previews, Certbot SSL redirects, WebSocket upgrade headers, and Docker DNS checks.

Written & verified by Chathura Prabashana · Updated November 2026

1. Adjust stack settings or load a test scenario2. Inspect live diagnostics3. Copy generated config
Quick-Test Scenarios:

1. Domain, Routing & Upstream

2. TLS, WebSockets & Directives

# /etc/nginx/sites-available/portal.example.com.conf
# Generated by OpsCheck DevTools — Validate with: sudo nginx -t && sudo systemctl reload nginx

server {
    listen 80;
    listen [::]:80;
    server_name portal.example.com;

    # Redirect all plaintext HTTP traffic permanently to HTTPS
    return 301 https://$host$request_uri;
}

server {
    listen 443 ssl http2;
    listen [::]:443 ssl http2;
    server_name portal.example.com;

    # Let's Encrypt Certbot TLS Certificates
    ssl_certificate     /etc/letsencrypt/live/portal.example.com/fullchain.pem;
    ssl_certificate_key /etc/letsencrypt/live/portal.example.com/privkey.pem;
    ssl_protocols       TLSv1.2 TLSv1.3;
    ssl_ciphers         HIGH:!aNULL:!MD5;
    ssl_prefer_server_ciphers on;

    client_max_body_size 50M;

    # Gzip compression for JSON, JS, CSS, and SVG responses
    gzip on;
    gzip_vary on;
    gzip_proxied any;
    gzip_comp_level 5;
    gzip_min_length 1024;
    gzip_types text/plain text/css application/json application/javascript text/xml application/xml image/svg+xml;

    # Baseline HTTP Security Headers
    add_header X-Frame-Options "SAMEORIGIN" always;
    add_header X-Content-Type-Options "nosniff" always;
    add_header Referrer-Policy "strict-origin-when-cross-origin" always;
    add_header Strict-Transport-Security "max-age=31536000; includeSubDomains" always;

    location / {
        proxy_pass http://127.0.0.1:8000;
        proxy_http_version 1.1;
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header X-Forwarded-Proto $scheme;
        proxy_set_header X-Forwarded-Host $host;
        proxy_set_header X-Forwarded-Port $server_port;
        proxy_set_header Connection "";

        proxy_connect_timeout 15s;
        proxy_send_timeout 120s;
        proxy_read_timeout 120s;
    }
}
$sudo nginx -t && sudo systemctl reload nginx
URL Routing TransformationPrefix Preserved
GET https://portal.example.com/usershttp://127.0.0.1:8000/users

Root location '/' forwards '/users' unchanged to upstream http://127.0.0.1:8000/users.

Configuration Diagnostics

  • infoRoot Proxy Path (/) Preserves Full Request URI

    GET https://portal.example.com/users -> Upstream receives http://127.0.0.1:8000/users. Root location '/' forwards '/users' unchanged to upstream http://127.0.0.1:8000/users.

  • infoSingle-Layer CORS Policy Reminder

    This configuration intentionally omits Access-Control-Allow-Origin headers so your upstream backend framework (Laravel, FastAPI, Express, ASP.NET Core) owns CORS cleanly without duplicate header rejections.

Runs locally in your browser. Domain names and upstream topology are never sent to a server.

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:

/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.

  1. 1Configure Proxy SSL and CSRF Trusted Origins in Django settings.py

    project/settings.py

    Tell 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.pypython
    ALLOWED_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 = True
  2. 2Serve Django /static/ and /media/ Directly From Nginx

    /etc/nginx/sites-available/portal.example.com.conf

    Add /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.confnginx
    location /static/ {
        alias /srv/django-app/staticfiles/;
        expires 30d;
        add_header Cache-Control "public, immutable";
    }
    
    location /media/ {
        alias /srv/django-app/media/;
        expires 7d;
    }
  3. 3Run Gunicorn Under systemd Bound to Localhost Port 8000

    /etc/systemd/system/gunicorn.service

    Launch 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=always
  4. 4Collect Static Files and Reload Nginx Without Downtime

    terminal

    Run collectstatic so Nginx has fresh admin and app assets on disk, verify file permissions for www-data, and test + reload Nginx.

    terminalbash
    python 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.

Pitfall 1

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.

Pitfall 2

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.

Pitfall 3

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.

Related Tools

Pair this Nginx reverse proxy block with healthcheck-gated Docker Compose orchestration and verified browser CORS headers:

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.
Browse all 10 Nginx guides →