Nginx – Strip Header on HTTP, Add Header on HTTPS

http-headersnginxPROXYsslweb-applications

I'm configuring an Nginx server so as to serve as a reverse proxy to serve a Django app (run on Gunicorn).

My problem is that I want my site secured with HTTPS, and so I want my Django app to be able to determine whether a connection is secure or not. I am using Django 1.4, so I do have access to the SECURE_PROXY_SSL_HEADER, which I configured as SECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROTOCOL', 'https').

Now, as mentionned by the documentation, I need to make sure that Nginx only adds the header when needed, and strips it when not. As I would like my Nginx configuration to be as DRY as possible, I'd rather not have two config files (one for port 80 and one for port 443).

Therefore, I'd like to know if there is a way in Nginx to determine whether the connection is https, and add (or strip) a header accordingly.

Best Answer

This solution does not describe how to strip a header on HTTP only, as asked in the question title.

A safe solution for your problem is to add

proxy_set_header  X-Forwarded-Protocol  $scheme;

It will set X-Forwarded-Protocol to http on HTTP requests and to https on HTTPS requests.

This makes sure that this header is overridden if the client set it, as required by https://docs.djangoproject.com/en/1.4/ref/settings/#secure-proxy-ssl-header.


NOTE: If you are sharing your Django project, please make sure to sufficiently warn users about this if you are including SECURE_PROXY_SSL_HEADER in settings.py, and best comment it out by default.