How to fix Django error: DisallowedHost at / Invalid HTTP_HOST header: ... You may need to add ... to ALLOWED_HOSTS
Asked Answered
A

6

181

I am trying to develop a website using Django framework and launched using DigitalOcean.com and deployed the necessary files into django-project.

I had to include static files into Django-project and After collecting static files, I tried to refresh my ip

I am including the tutorials which I have used to create the website. https://www.pythonprogramming.net/django-web-server-publish-tutorial/

I am getting the following error :

DisallowedHost at / Invalid HTTP_HOST header: '198.211.99.20'. You may need to add u'198.211.99.20' to ALLOWED_HOSTS.

Can somebody help me to fix this ? This is my first website using Django framework.

Adige answered 14/11, 2016 at 5:33 Comment(2)
That may also be your Floating IP address on DigitalOcean.Conch
Can I use my external IP for starting the server?Drinking
B
292

The error log is straightforward. As it suggested,You need to add 198.211.99.20 to your ALLOWED_HOSTS setting.

In your project settings.py file,set ALLOWED_HOSTS like this :

ALLOWED_HOSTS = ['198.211.99.20', 'localhost', '127.0.0.1']

For further reading read from here.

Burnsides answered 14/11, 2016 at 5:41 Comment(14)
Now getting the following error Request URL: 198.211.99.20 Exception Type:TemplateDoesNotExist Exception Value: personal/home.html Exception Location: /usr/local/lib/python2.7/dist-packages/django/temp‌​late/loader.py in get_template, line 25 I have my templates in the following folder /home/django/django_project/personal/templates/personalAdige
@Kathir There are many examples of that error.Just google it and if the problem still continues,then please ask it as a separate question,comments are not very descriptive.Burnsides
This definitely works but is bad practice as you should always use a .env fileShushan
@AbhishekJebaraj could you please explain a little more or share a link with more explanation?Maris
@JesusAlmaral Here you go docs.djangoproject.com/en/1.11/topics/settings/… :)Burnsides
@JesusAlmaral A .env file is a local file containing passwords and other sensitive information. If you put all this sensitive information inside your code itself then it could get compromised. Thus we use this local file .env and everyone stores with their own passwords etc locallyShushan
The problem is that I suspect these events induced by various bots I think. I don't want to pollute my settings.py with all kind of bot's IPs, especially they can vary. I rather want to suppress this message all togetherFabe
@CsabaToth If you go to the provided link, you can see that you can suppress the warning by adding ALLOWED_HOSTS = [] so, please read the whole answer before downvoting.Burnsides
I don't want to empty the ALLOWED_HOSTS either, but I'll remove the downvoteFabe
I run my project using AWS Elastic Beanstalk and have multiple server instances. I get these errors as well. I can't just add the IPs to fix the problem because they change constantly. I would be updating it everyday.Stranglehold
I used dotenv to store the values locally, and then also include them as environment variables on production: npmjs.com/package/dotenv Like this: ALLOWED_HOSTS = [ 'localhost', 'app.mysite.com', os.environ.get('SERVER_IP') ]Explication
FWIW, in our case, all accesses by the naked IP address are dubious. Our solution was to configure the web server to reject all Host headers not matching the ones Django accepts.Fishman
If I add the ip address 198.211.99.20 to ALLOWED_HOSTS after the error message: “Invalid HTTP_HOST header: '198.211.99.20' that would solve the DISALLOWED HOST problem. But wouldn't that cause problems in the future since I'm using auto scaling? Since that could lead to new instances being created with new IP addresses if there is enough trafic. So i'm gonna have to hard code the new IP addresses into ALLOWED_HOSTS every time that happens?Wivina
ALLOWED_HOSTS = ['*'] worked for me.Endive
T
9

settings.py

ALLOWED_HOSTS = ['*'] # if you are in dev or docker

Don't do this in production if you are not using docker, just put the IP address.

Talton answered 23/5, 2018 at 17:1 Comment(7)
As pydanny said "...don't leave it as such once you get this figured out. The reason is that makes Django potentially vulnerable to HTTP_HOST header attacks. And automated scripts scour the internet to check if sites have this vulnerability." github.com/pydanny/cookiecutter-django/issues/…Highlands
Lol, that is for development env. in production only need set DEBUG=False.Talton
You do not want to use '*' for production. This completely bypasses the reason and security of the allowed hosts.Passivism
@AndyPoquette generally you're right, but using docker (and not exposing the backend's port, but using a reverse proxy like nginx) it's OK to use '*' even for production.Wagers
Never, NEVER do this! Allowed * is a primary security error. Only do this in development mode!Unhallow
@Wagers is this correct? I'm using Django with docker in production and I'm receiving some emails with that error. Do you think it's a good idea anyway? You have an article talking about that?Orphaorphan
Depending on how you expose your docker container this can still be a security issue. Its best to actually connfigure the correct IP addresses / domain names instead.Hasheem
S
2

In your project settings.py file,set ALLOWED_HOSTS like this :

ALLOWED_HOSTS = ['62.63.141.41', 'namjoosadr.com']

and then restart your apache. in ubuntu:

/etc/init.d/apache2 restart
Siclari answered 28/10, 2020 at 9:14 Comment(0)
T
1

You can add ALLOWED_HOSTS to your settings file or env file:

ALLOWED_HOSTS = [".localhost", "127.0.0.1", "[::1]"]
Triangulation answered 11/8, 2023 at 21:15 Comment(0)
C
0

if no other answer work you can try modifying manage.py and add this three lines

from django.utils.regex_helper import _lazy_re_compile
import django.http.request
django.http.request.host_validation_re = _lazy_re_compile(r"[a-zA-z0-9.:]*")

to end up having something like this:

import os
import sys

from django.utils.regex_helper import _lazy_re_compile
import django.http.request    
django.http.request.host_validation_re = _lazy_re_compile(r"[a-zA-z0-9.:]*")

def main():
    """Run administrative tasks."""
    os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'project01.settings')
    try:
        from django.core.management import execute_from_command_line
    except ImportError as exc:
        raise ImportError(
            "Couldn't import Django. Are you sure it's installed and "
            "available on your PYTHONPATH environment variable? Did you "
            "forget to activate a virtual environment?"
        ) from exc
    execute_from_command_line(sys.argv)


if __name__ == '__main__':
    main()

as it is explained in this post: How to Solve "The domain name provided is not valid according to RFC 1034/1035" in Django during Development

Contrive answered 3/2, 2023 at 21:2 Comment(0)
W
0

I was testing my Django app on minikube and because of the probes, it was failing with the following error:

Invalid HTTP_HOST header: '10.244.0.8:8080'. You may need to add '10.244.0.8' to ALLOWED_HOSTS.
Bad Request: /

I added the httpHeaders in my probes and it worked after that.

Before:

livenessProbe:
  httpGet:
    path: / # Replace with an endpoint that returns a 200 status code if the app is healthy
    port: 8080
  initialDelaySeconds: 10 # Delay before the first probe is executed
  periodSeconds: 10 # How often to perform the probe
readinessProbe:
  httpGet:
    path: / # Replace with an endpoint that indicates readiness
    port: 8080
  initialDelaySeconds: 5 # Delay before the first probe is executed
  periodSeconds: 5 # How often to perform the probe

After:

livenessProbe:
  httpGet:
    path: / # Replace with an endpoint that returns a 200 status code if the app is healthy
    port: 8080
    httpHeaders:
    - name: Host
      value: localhost
  initialDelaySeconds: 10 # Delay before the first probe is executed
  periodSeconds: 10 # How often to perform the probe
readinessProbe:
  httpGet:
    path: / # Replace with an endpoint that indicates readiness
    port: 8080
    httpHeaders:
    - name: Host
      value: localhost
  initialDelaySeconds: 5 # Delay before the first probe is executed
  periodSeconds: 5 # How often to perform the probe
Weiss answered 5/11, 2023 at 17:51 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.