I continuously receive `Invalid HTTP_HOST header` error email after I upgrade my django site from http to https
Disabling DisallowedHost
host warnings as suggested in the other answer is not the correct solution in my opinion. There is a reason why Django gives you those warnings - and it is better for you to block those requests before they reach Django.
You created a new server block in your nginx configuration. Because it is the only HTTPS server you have defined, it becomes the default server for that port. From the documentation:
The
default_server
parameter, if present, will cause the server to become the default server for the specifiedaddress:port
pair. If none of the directives have thedefault_server
parameter then the first server with theaddress:port
pair will be the default server for this pair.
This explains why you are suddenly seeing all these invalid host errors. Any bot that now tries to connect to your server over HTTPS will end up using this default server. Because many bots will be using fake host names or just your server IP (neither of which are in ALLOWED_HOSTS
) this causes the warnings in Django.
So what is the solution? You can create a separate server block that handles all such invalid requests:
server { listen 443 ssl default_server; server_name _; return 444;}
444
is a special response status used by nginx to disconnect invalid requests.
Once you add this block, it will be used for all requests that don't match the host headers that you want to respond to, and anything trying to connect with an invalid host will not be able to connect.
Django meanwhile will stop seeing requests for invalid hosts.
This is probably because there may be bot scripts running which are targeting your server with different HTTP_HOST headers (this is common). and in django you have Allowed Hosts set to a particular host. So if a Host Header different from one specified in Allowed Hosts come then django would give 400 error.By default django loggers are configured to send mail on each error. To stop getting the mails you need to configure loggers in django and add the following logger'django.security.DisallowedHost': { 'handlers': ['null'], 'propagate': False,},
Refer https://www.calazan.com/how-to-disable-the-invalid-http_host-header-emails-in-django/