Commit c36e9d4
Stuart MacKay
Stop invalid host header errors being raised by Django
When a client uses the IP address instead of the domain name Django will
raise an `Invalid HTTP_HOST header` error since the IP address is not
listed in the ALLOWED_HOSTS setting.
This situation occurs most commonly with bots probing the site for security
holes. If you log Django errors using Sentry then a constant stream of these
errors will be reported. At best they are a distraction.
The solution is for nginx to terminate the connection immediately so the
request never reaches Django. This is done simply by matching the host
header with the sites IP address and raising the HTTP error 444 which is
unique to nginx and instructs the server to close the connection immediately.
Nothing is returned to the client so it effectively gets a status code of 0.
The problem and the solution is described clearly in the following post:
https://www.borfast.com/blog/2020/07/06/invalid-http_host-header-errors-in-django-and-nginx/
There a related problem that triggers same Invalid HTTP_HOST header error
when the client does not set the HOST header at all. This is discussed and
a solution given in this Stack Overflow question (the URL was truncated
but is still valid) https://stackoverflow.com/questions/25370868/
The test for using an IP address instead of a domain name was added to post
80 and 443. It should have been possible to let the redirect from HTTP to
HTTPS complete and have test in a single location however since the intent
of the client is generally malicious it didn't seem right to waste more
energy than was necessary, hence the duplication of the check.1 parent debc7cf commit c36e9d4
1 file changed
+16
-1
lines changed| Original file line number | Diff line number | Diff line change | |
|---|---|---|---|
| |||
10 | 10 | | |
11 | 11 | | |
12 | 12 | | |
| 13 | + | |
| 14 | + | |
| 15 | + | |
| 16 | + | |
| 17 | + | |
| 18 | + | |
| 19 | + | |
| 20 | + | |
13 | 21 | | |
14 | 22 | | |
15 | 23 | | |
| |||
31 | 39 | | |
32 | 40 | | |
33 | 41 | | |
| 42 | + | |
| 43 | + | |
| 44 | + | |
| 45 | + | |
| 46 | + | |
| 47 | + | |
| 48 | + | |
34 | 49 | | |
35 | 50 | | |
36 | 51 | | |
| |||
95 | 110 | | |
96 | 111 | | |
97 | 112 | | |
98 | | - | |
| 113 | + | |
99 | 114 | | |
100 | 115 | | |
101 | 116 | | |
| |||
0 commit comments