[Django]-Django ERROR: Invalid HTTP_HOST header: u'/run/myprojectname/gunicorn.sock:'

30đź‘Ť

âś…

Seems like

proxy_set_header Host $http_host

should be changed to

proxy_set_header Host $host

and server_name should be set appropriately to the address used to access the server. If you want it to catch all, you should use server_name www.domainname.com "" (doc here).

I’m not certain, but I think what you’re seeing happens if the client doesn’t send a Host: header. Since nginx receives no Host: header, no Host: header gets passed up to gunicorn. At this point, I think gunicorn fills in the Host: as the socket path and tells Django this, since that’s the connection used. Using $host and setting the server_name in nginx should ensure the Host: is correctly passed to gunicorn and resolve this problem.

As for the email, according to the commit in the ticket you linked, it looks like emails are still being sent for disallowed hosts. Added to the doc was also a suggested a way to disable the emails being sent:

    'loggers': {
        'django.security.DisallowedHost': {
        'handlers': ['null'],
        'propagate': False,
        }
    },
👤user193130

19đź‘Ť

I have come across some comments that suggest that suppressing the emails is not a good idea because it does not directly address the issue. The most effective solution I have found is to addd the following to your nginx settings:

server {

    ...

    ## Deny illegal Host headers
    if ($host !~* ^(mydomain.com|www.mydomain.com)$ ) {
        return 444;
    }
}

For more information: https://snakeycode.wordpress.com/2015/05/31/django-error-invalid-http_host-header/

The blog post references this question.

👤Ernest Jumbe

9đź‘Ť

I know this is an old question, but the issue happened to me just today. The recommended solution on Django docs is to add a “catch all” nginx server in your nginx config:

server {
    listen 80 default_server;
    return 444;
}

The official nginx docs recommend the same solution, give or take some syntax nuances.

This way, the request doesn’t go to django, the connection gets shutdown immediately when nginx receives a malformed request.

👤Laurent S

Leave a comment