Saurabh Verma
Saurabh Verma

Reputation: 6728

django ALLOWED_HOSTS not working

My settings.py file contains:

DEBUG = False
ALLOWED_HOSTS = [u'mydomainxxx.com']

Howevever, I'm able to fire a curl request like this: curl -X GET https://mydomainxxx.com/api/ -H 'Authorization: Token some token' and am getting the response.

I was hoping that using ALLOWED_HOSTS will prevent commands like curl to get response from my API. Is this a normal behaviour ?

Upvotes: 3

Views: 7647

Answers (3)

Rehan
Rehan

Reputation: 31

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

Upvotes: 0

Saurabh Verma
Saurabh Verma

Reputation: 6728

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>')

Upvotes: 2

Selcuk
Selcuk

Reputation: 59184

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.

Upvotes: 6

Related Questions