Home > Blockchain >  DisallowedHost at / Invalid HTTP_HOST header: [IP] ; You may need to add [IP] to ALLOWED_HOSTS
DisallowedHost at / Invalid HTTP_HOST header: [IP] ; You may need to add [IP] to ALLOWED_HOSTS

Time:07-12

I want to deploy my Django app and I already used gunicorn, nginx and supervisor and stored on AWS EC2

Here is the snippet of my settings.py

DEBUG = False

ALLOWED_HOSTS = ['<my_ip>', '<my_ip>.ap-southeast-1.compute.amazonaws.com']

I have settings_prod.py and settings_dev.py

settings_prod.py

DEBUG = False

ALLOWED_HOSTS = [
    '<my_ip>', '<my_ip>.ap-southeast-1.compute.amazonaws.com']

From my wsgi.py

from django.core.wsgi import get_wsgi_application

os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'votingapp.settings_prod')

I put the correct host address and it still got the same error:

Exception Type: DisallowedHost
Exception Value:    
Invalid HTTP_HOST header: '<ip>'. You may need to add '<ip>' to ALLOWED_HOSTS.

The problem is it uses settings from settings_dev.py which is not my ideal sequence. I want the supervisor or settings_dev.py to allow my IP to host the site.

Any help would be appreciated.

CodePudding user response:

Add your IP in ALLOWED HOSTS

DEBUG = False

ALLOWED_HOSTS = [
    'your IP',
]

Then your can run your server as python manage.py runserver yourIP:port

CodePudding user response:

I had the same issue, and I've solved it with following steps:

  1. I use .env files with my project (for managing it I use python-decouple package);
  2. I separate all my settings to dev and prod py files with base common python file.
  3. Next, I import all settings from .base, .dev and .prod and manage them with PROJECT env var (if env var set to dev, use dev settings).

__init__.py file:

from .base import *

if config("PROJECT") == "prod":
    from .prod import *
else:
    from .dev import *

config set in base.py:

from decouple import AutoConfig

PROJECT_ROOT = Path(__file__).resolve().parent.parent
BASE_DIR = PROJECT_ROOT.parent

ENV_FILE_PATH = BASE_DIR.parent / '.env'
config = AutoConfig(ENV_FILE_PATH)

structure of settings sub-package in my django project:

...
settings
  ├── __init__.py
  ├── base.py
  ├── dev.py
  └── prod.py

If you use AWS ES2, then you probably already have env vars in your project, so you can just replace python-decouple by your solution (like os.environ as default) and then manage your settings with your custom setted env var.

  • Related