Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django + uwsgi + nginx + SSL

I am using Django on DotCloud which uses Django on top of uwsgi + nginx. I am trying to redirect all http traffic to https which is leading to a redirect loop. I am using the following http configuration

if ($http_x_forwarded_port != 443) { rewrite ^ https://$http_host/; }

It seems that Django doesn't understand that it is operating on https and the header is not preserved. It redirects https://url.com/ to http://url.com/accounts/login/ which is redirecting again and again leading to a redirect loop. I am not really an expert in nginx and do not understand it well enough. What can I be doing wrong?

In short how do I run redirect http to https in django running on top of uswsgi and nginx.

like image 463
Rewolverine Avatar asked Jul 21 '11 21:07

Rewolverine


People also ask

Is Nginx required for uWSGI?

Can I then ditch NGINX? uWSGI could be used as a standalone web server in production, but that is not it's intentional use. It may sound odd, but uWSGI was always supposed to be a go-between a full-featured web server like NGINX and your Python files.

Which is better Gunicorn or uWSGI?

Gunicorn and uWSGI are primarily classified as "Web Servers" and "Web Server Interface" tools respectively. Gunicorn and uWSGI are both open source tools. Gunicorn with 5.96K GitHub stars and 1.12K forks on GitHub appears to be more popular than uWSGI with 2.5K GitHub stars and 541 GitHub forks.

What is nginx server in Django?

Nginx defines itself as a high-performance web server and a reverse proxy server. It's worth breaking this down because it helps explain Nginx's relation to Gunicorn and Django. Firstly, Nginx is a web server in that it can serve files to a web user or client.


2 Answers

I needed a bit more to make Django aware that it should be using https.

In settings.py I added SECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROTO', 'https')

And in the nginx configuration

location / {
    proxy_set_header X-Forwarded-Proto https;
    include uwsgi_params;
    uwsgi_param UWSGI_SCHEME https;
    uwsgi_pass_header X_FORWARDED_PROTO;
    uwsgi_pass unix:///path/to/socket;
}
like image 197
sellonen Avatar answered Oct 05 '22 06:10

sellonen


server {
  listen  80;
  server_name  yourhttphost;
  rewrite ^ https://yourhttpshost$request_uri? permanent; #301 redirect
}
server {
  listen 443;
  server_name  yourhttpshost;
  ........
  the rest
  ........
}

Using "if" in nginx config is a very bad idea!

like image 28
MechanisM Avatar answered Oct 05 '22 06:10

MechanisM