Nginx as a reverse proxy helps direct web traffic to your Django app safely and efficiently. It acts like a friendly gatekeeper that manages requests from users to your server.
Nginx as reverse proxy in Django
server {
listen 80;
server_name yourdomain.com;
location / {
proxy_pass http://127.0.0.1:8000;
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_pass tells Nginx where your Django app is running (usually localhost with port 8000).
Headers like X-Real-IP help your Django app know the real user IP address.
location /static/ {
alias /path/to/your/staticfiles/;
}server {
listen 443 ssl;
server_name yourdomain.com;
ssl_certificate /etc/ssl/certs/yourcert.pem;
ssl_certificate_key /etc/ssl/private/yourkey.pem;
location / {
proxy_pass http://127.0.0.1:8000;
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;
}
}This Nginx config sends all normal web requests to the Django app running on localhost port 8000. Static files are served directly from the specified folder for faster loading.
server {
listen 80;
server_name example.com;
location /static/ {
alias /home/user/myproject/static/;
}
location / {
proxy_pass http://127.0.0.1:8000;
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;
}
}Remember to collect static files in Django using python manage.py collectstatic before serving them with Nginx.
Make sure your Django app is running and accessible on the port Nginx proxies to.
Use firewall rules to allow traffic only through Nginx, not directly to Django app port.
Nginx as a reverse proxy forwards user requests to your Django app safely and efficiently.
It can serve static files directly, improving speed and reducing load on Django.
It helps add HTTPS and security features easily in front of your Django app.