Answer the question
In order to leave comments, you need to log in
How to properly configure HTTPS for Nginx and Django?
I'm setting up a server for production. You need to configure the site to work with HTTPS only. There is a directive in the nginx config
proxy_redirect off;
proxy_set_header X-Forwarded-Proto $scheme;
rewrite ^ https://$server_name$request_uri? permanent;
ATsettings.py
SECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROTO', 'https')
SECURE_SSL_REDIRECT = True
proxy_redirect off;
proxy_set_header X-Forwarded-Proto $scheme;
designed to remedy the situation. Answer the question
In order to leave comments, you need to log in
Most likely at you requests get to cyclic redirection. If I posted the entire nginx config, it would become clearer.
I have a bunch of Django -> Gunicorn -> Nginx
Nginx listens on 80 and 443 external ports. When accessed on 80, it redirects to 443.
Django listens on a custom port through Gunicorn, where it accepts HTTP requests. I didn't add special options for SSL in Djang's settings.
My nginx config for django.
server {
listen 80;
server_name <site_name>;
return 301 https://<site_name>$request_uri;
}
server {
server_name <site_name>;
listen <site_name>:443 ssl;
gzip on;
gzip_disable "msie6";
gzip_types text/plain text/css application/json application/x-javascript text/xml application/xml application/xml+rss text/javascript application/javascript;
ssl_certificate /<path_to_ssl>/fullchain.pem;
ssl_certificate_key /<path_to_ssl>/privkey.pem;
ssl_trusted_certificate /<path_to_ssl>/chain.pem;
ssl_stapling on;
ssl_stapling_verify on;
resolver 127.0.0.1 8.8.8.8;
add_header Strict-Transport-Security "max-age=31536000";
add_header Content-Security-Policy "img-src https: data:; upgrade-insecure-requests";
expires max;
location /static/ {
alias /<project_path>/static/;
expires 30d;
}
location /media/ {
alias /<project_path>/media/;
expires 30d;
}
location / {
client_max_body_size 0;
proxy_pass http://<local_ip>:<port>/;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header REMOTE_ADDR $remote_addr;
proxy_set_header Host $host;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
expires 1h;
}
}
server {
server_name www.<site_name>;
listen www.<site_name>443 ssl;
access_log off;
ssl_certificate /<path_to_ssl>/fullchain.pem;
ssl_certificate_key /<path_to_ssl>/privkey.pem;
ssl_trusted_certificate /<path_to_ssl>/chain.pem;
ssl_stapling on;
ssl_stapling_verify on;
resolver 127.0.0.1 8.8.8.8;
add_header Strict-Transport-Security "max-age=31536000";
expires max;
return 301 https://<site_name>$request_uri;
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question