How to disable the 'Invalid HTTP_HOST header' emails in Django
Ever get these annoying admin emails?
Invalid HTTP_HOST header: '104.131.142.135'. You may need to add u'104.131.142.135' to ALLOWED_HOSTS. Request repr(): <WSGIRequest path:/, GET:<QueryDict: {}>, POST:<QueryDict: {}>, COOKIES:{}, META:{'HTTP_CONNECTION': 'close', 'HTTP_HOST': '104.131.142.135', ...
The reason you're getting this is because someone's trying to access your site via a host not listed in your ALLOWED_HOSTS setting. In my case, for this blog, I have just this:
ALLOWED_HOSTS = ['.calazan.com']
So if someone visits my site using a host that doesn't end with calazan.com, it will throw a Bad Request (400) error. Since I have my logger set to email me all ERROR level logs, I will get an alert.
An easy test for me is by simply visiting my site using its IP address. If you allow the server's IP address, you can test this by modifying your /etc/hosts file, adding an entry pointing to the IP address of your server using some random host, and then going to that host on your web browser. For example:
# /etc/hosts 1.2.3.4 www.example.com
Now if you visit www.example.com and it hits your site, Django will throw a 400 and you will get an email notification.
The good news is you can easily silence these alerts in your Django log settings, you don't need to touch your web server configuration:
... 'handlers': { 'null': { 'level': 'DEBUG', 'class': 'logging.NullHandler', }, 'console': { 'level': 'INFO', 'class': 'logging.StreamHandler', 'formatter': 'default', }, 'mail_admins': { 'level': 'ERROR', 'filters': ['require_debug_false'], 'class': 'django.utils.log.AdminEmailHandler', } }, 'loggers': { # Silence SuspiciousOperation.DisallowedHost exception ('Invalid # HTTP_HOST' header messages). Set the handler to 'null' so we don't # get those annoying emails. 'django.security.DisallowedHost': { 'handlers': ['null'], 'propagate': False, }, 'django.request': { 'handlers': ['mail_admins'], 'level': 'ERROR', 'propagate': True, }, '': { 'handlers': ['console', ], 'level': 'INFO', } } ...
So basically, add a null handler and set django.security.DisallowedHost to use that null handler and those errors will get ignored.