Search code examples
pythondjangoapachepythonanywhere

How to resolve SuspiciousOperation: Invalid HTTP_HOST header error?


I was trying to deploy my django app on pythonanywhere.

Traceback from apache error log:

2013-07-23 09:31:35,058 :Internal Server Error: /favicon.ico
Traceback (most recent call last):
  File "/usr/local/lib/python2.7/dist-packages/django/core/handlers/base.py", line 89, in get_response
    response = middleware_method(request)
  File "/usr/local/lib/python2.7/dist-packages/django/middleware/common.py", line 55, in process_request
    host = request.get_host()
  File "/usr/local/lib/python2.7/dist-packages/django/http/__init__.py", line 179, in get_host
    "Invalid HTTP_HOST header (you may need to set ALLOWED_HOSTS): %s" % host)
SuspiciousOperation: Invalid HTTP_HOST header (you may need to set ALLOWED_HOSTS): monty_singh.pythonanywhere.com

I tried ['*'] and ['monty_singh.pythonanywhere.com'] as values for ALLOWED_HOSTS but the app is still not working. No matter what value I set for ALLOWED_HOSTS I get the same error.


Solution

  • When Django validates the host from the HTTP request it attempts to match it against the following regex which you can find in the source here:

    host_validation_re = re.compile(r"^([a-z0-9.-]+|\[[a-f0-9]*:[a-f0-9:]+\])(:\d+)?$")
    

    The underscore in your username is causing Django to reject the host name on the request. You can create a new PythonAnywhere account with a new username or use a different web framework.