I continuously receive `Invalid HTTP_HOST header` error email after I upgrade my django site from http to https

后端 未结 3 920
醉梦人生
醉梦人生 2020-12-09 09:24

Recently, I upgrade one of my django sites from http to https. However, after that, I continuously receive Invalid HTTP_HOST header error email while before I n

3条回答
  •  庸人自扰
    2020-12-09 10:13

    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 specified address:port pair. If none of the directives have the default_server parameter then the first server with the address: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.

提交回复
热议问题