Nginx Configuration for Django

A snippet showing how to configure Nginx for Django deployment.


# /etc/nginx/sites-available/project.conf (Gunicorn via Unix socket)

server {
    listen 80;
    server_name example.com www.example.com;

    # Max upload size
    client_max_body_size 20m;

    # Serve static files
    location /static/ {
        alias /srv/project/staticfiles/;
        access_log off;
        expires 7d;
    }

    # Serve media files (user uploads)
    location /media/ {
        alias /srv/project/media/;
        access_log off;
        expires 7d;
    }

    # Proxy all other requests to Gunicorn (Unix socket)
    location / {
        include proxy_params;
        proxy_set_header Host $host;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header X-Forwarded-Proto $scheme;
        proxy_pass http://unix:/run/gunicorn.sock;
    }
}
      

# Enable site and test config (Debian/Ubuntu)

sudo ln -s /etc/nginx/sites-available/project.conf /etc/nginx/sites-enabled/
sudo nginx -t
sudo systemctl reload nginx
      

# Optional: Let's Encrypt TLS (certbot + nginx)

sudo apt-get install -y certbot python3-certbot-nginx
sudo certbot --nginx -d example.com -d www.example.com

# Auto-renew (usually installed by certbot)
sudo systemctl status certbot.timer
      
Explanation:
  • Use alias for static/media directories outside the web root.
  • Prefer Unix sockets for Gunicorn; they reduce TCP overhead on the same host.
  • Ensure correct proxy headers (Host, X-Forwarded-*) so Django builds absolute URLs correctly.
  • After enabling HTTPS, set Django security settings (e.g., SECURE_SSL_REDIRECT).
  • Category Deployment & Settings
  • Total Views 755
  • Last Modified 23 November, 2025
  • Tags #deployment #nginx #server #proxy
Previous snippet
Gunicorn Deployment Example
Next snippet
Enable Query Debugging
Never miss a story on Django.wiki

Subscribe for fresh tutorials, snippets, and updates.

By subscribing you agree to our Privacy Policy.