Gem #4: To forward or not to forward the hostname
We recently published some details of our nginx configuration and we would like to give you an overview of some more gems that it contains.
If you remember gem #2 from the previous article, we are using landing pages with http (not https) for some domains like digitalglarus.ch, but use https for every subpage below ungleich.ch (because we like to provide as many sites with ssl as possible).
Django: Allowed hosts
We are using various domain names, however our django app uses only the following allowed hosts:
ALLOWED_HOSTS = [
".ungleich.ch",
]
If a request is received with a different host header, django will refuse to serve the request. As we have to handle the landing pages in nginx, we prefer not to duplicate every domain we add in nginx into our django configuration.
Nginx and uwsgi_pass
Nowadays nginx ships with a pre-configured set of uwsgi_param directives that you can include using
include uwsgi_params;
However this default setup also forwards the hostname. We had a look at the file and saw that SERVER_NAME is being sent and tried to replace it by using
uwsgi_param SERVER_NAME $ungleich_servername;
(and we setup $ungleich_servername at a different position - more about this in our next blog post).
When testing this setup using
curl -H "Host: digitalglarus.ch" dynamicweb.ungleich.ch
we still saw the hostname digitalglarus.ch in the uwsgi app. What happened? Well, reading the python code revealed that before SERVER_NAME the header HTTP_HOST is being checked. But we did not pass this header!
Nginx and uwsgi_pass_request_headers
It turns out that by default nginx is forwarding all headers to the uwsgi app - including HTTP_POST. We turned that behaviour off using the following directive:
uwsgi_pass_request_headers off;
And voila: it works!
For production however, we do not turn off the request headers, but overwrite the HTTP_HOST header as following:
include uwsgi_params;
uwsgi_param SERVER_NAME $ungleich_servername;
uwsgi_param HTTP_HOST $ungleich_servername;
This way we can setup the variable $ungleich_servername to a subdomain of ungleich.ch and do not need to modify the settings.py for any URL that we add.