Ever since I deployed a site running Django 1.7 alpha (checked out from Git), I\'ve been occasionally receiving error messages with titles like:
\"Inv
Another way to block requests with an invalid Host header before it reaches Django is to use a default Apache config with a <VirtualHost>
that does nothing but return a 404.
<VirtualHost *:80>
</VirtualHost>
If you define this as your first virtual host (e.g. in 000-default.conf) and then follow it with your 'real' <VirtualHost>
, complete with a <ServerName>
and any <ServerAlias>
entries that you want to match, Apache will return a 404 for any requests with a Host
header that does not match <ServerName>
or one of your <ServerAlias>
entries. The key it to make sure that the default, 404 <VirtualHost>
is defined first, either by filename ('000') or the first entry in your config file.
I like this better than the popular solution above because it is very explicit and easy to extend.
Here's NGINX example that should prevent your django from receiving rubbish requests.
server {
listen 80 default_server;
server_name _;
return 418;
}
server {
listen 80;
# This will keep Django from receiving request with invalid host
server_name <SERVER_IP> your.domain.com;
...
In setting.py set:
ALLOWED_HOSTS = ['yourweb.com']
Using Apache 2.4, there's no need to use mod_setenvif. The HTTP_HOST is already a variable and can be evaluated directly:
WSGIScriptAlias / /path/to/wsgi.py
<Directory /path/to>
<Files wsgi.py>
Require expr %{HTTP_HOST} == "example.com"
</Files>
</Directory>
The django docs address this specifically. They recommend putting this in your logging settings
LOGGING = {
"handlers": {
# ...
"null": {
"class": "logging.NullHandler",
},
},
"loggers": {
# ...
"django.security.DisallowedHost": {
"handlers": ["null"],
"propagate": False,
},
},
}