Skip to content

Instantly share code, notes, and snippets.

@linuxkathirvel
Last active April 6, 2023 20:31
Show Gist options
  • Select an option

  • Save linuxkathirvel/431e91b059a9f573df321c9718be9db2 to your computer and use it in GitHub Desktop.

Select an option

Save linuxkathirvel/431e91b059a9f573df321c9718be9db2 to your computer and use it in GitHub Desktop.
How to fix ERR_TOO_MANY_REDIRECTS issue in Django+Gunicorn+NGINX?

How to fix ERR_TOO_MANY_REDIRECTS issue in Django+Gunicorn+NGINX?

NGINX configuration

server {
        listen 80;
        server_name kathirvel.com;
        return 301 https://kathirvel.com;
        client_max_body_size 1024M;
}
server {
        listen 443 ssl;
        ssl on;
        ssl_certificate /cert/.kathirvel.com.cer;
        ssl_certificate_key /cert/_.kathirvel.com.key;
        server_name kathirvel.com;   # substitute by your FQDN and machine's IP address
        client_max_body_size 1024M;

        # Django static files. You should run 'django manage.py collectstatic'
        location /static  {
                autoindex on;
                alias /data/staticfiles;
        }
    
    # Finally, send all non-media requests to the Django server.
    location / {
        proxy_pass http://kathirvel.com:9100;
        proxy_redirect off;
        proxy_set_header X-Forwarded-Proto $scheme;
        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_read_timeout 1000000;
    }

    error_page 404 /404.html;
    location = /404.html {
        root /etc/nginx;
        internal;
    }

    error_page 500 502 503 504 /500.html;
    location = /500.html {
        root /etc/nginx;
        internal;
    }
}

Add below line in settings.py

SECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROTO', 'https')

Restart Gunicorn

Restart NGINX

References

https://stackoverflow.com/questions/41483068/djangos-httpresponseredirect-is-http-instead-of-https/41488430 https://djangodeployment.com/2017/01/24/fix-djangos-https-redirects-nginx/

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment