[Django]-Django ALLOWED_HOSTS not working

2👍

✅

Just for anyone who would like to filter on referer url and not on ip address, we can use the following middleware:

from django.conf import settings
from django import http

class AllowHostsMiddleware(object):

    def process_request(self, request):
        referer_url = request.META.get('HTTP_REFERER','')
        if referer_url.startswith(settings.ALLOWED_REFERER_URL):
            return None
        return http.HttpResponseForbidden('<h1>Forbidden</h1>')

6👍

You are confusing the ALLOWED_HOSTS setting with something else. It denotes the hostnames that your server will listen to; not the hostnames of connecting hosts. There is no built in method to prevent it but you can easily write a middleware to check connecting hostnames.

Your current setting will prevent this from getting a response:

curl -X GET http://another_domainxxx.com/api/ -H 'Authorization: Token some token' 

even if both mydomainxxx.com and another_domainxxx.com will resolve to the same IP Address.

0👍

Add your domain or ip to the Allowed_Hosts
and then type the following command

sudo systemctl restart nginx

then

sudo systemctl restart gunicorn and

Leave a comment