Skip to content

Instantly share code, notes, and snippets.

@eezis
Last active June 28, 2023 16:23
Show Gist options
  • Save eezis/7586964 to your computer and use it in GitHub Desktop.
Save eezis/7586964 to your computer and use it in GitHub Desktop.
Resolving Bad Request (400) when using Django on an EC2 instance DEBUG
This gist pertains to a Bad Request(400) error when trying to access an EC2 instance running django . . .
I set up an EC2 server, installed django, started runserver and tested. The result was
Bad Request (400)
When using Django 1.5 and higher, if you specify DEBUG=False in the settings.py file, you must also specify ALLOWED_HOSTS
or you will recieve a "Bad Request (400)" error message when attempting to retrieve a page.
On an Amazone EC2 instance, if you are ***testing*** with the public DNS, then you should include the public DNS as one of the allowed hosts.
--- example ---
DEBUG = False
ALLOWED_HOSTS = ['.yourdomain.com', 'ec2-XX-XX-XX-XXX.us-west-2.compute.amazonaws.com',]
--- end ---
If have SSH'ed into the server and wish to perform on-server testing you should include 'localhost' as well:
python manage.py runserver 0:8000
then . . .
curl http://localhost:8000/
or . . .
telnet localhost 8000 (then type GET / and hit enter twice)
If that does not work add 'localhost' to your ALLOWED_HOSTS file.
ALLOWED_HOSTS = ['.yourdomain.com', 'ec2-XX-XX-XX-XXX.us-west-2.compute.amazonaws.com', 'localhost',]
========
NOTE WELL: If you reboot your EC2 instance, when it reboots it will have a different public DNS and you
will need to update your ALLOWED_HOSTS accordingly.
See the 1.5 release notes for more:
https://docs.djangoproject.com/en/dev/releases/1.5/#allowed-hosts-required-in-production
@iamrahulrnair
Copy link

+1

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment