[Fixed]-Django ALLOWED_HOSTS for Amazon ELB


Another simple solution would be to write a custom MIDDLEWARE which will give the response to ELB before the ALLOWED_HOSTS is checked. So now you don’t have to load ALLOWED_HOSTS dynamically.

The middleware can be as simple as:


from django.http import HttpResponse
from django.utils.deprecation import MiddlewareMixin

class HealthCheckMiddleware(MiddlewareMixin):
    def process_request(self, request):
        if request.META["PATH_INFO"] == "/ping/":
            return HttpResponse("pong")



Django Middleware reference https://docs.djangoproject.com/en/dev/topics/http/middleware/


Fetching AWS internal IPs and adding to the ALLOWED_HOST is not the best solution. Since this Fetching will happen only on application reload. ELB IPs can change anytime.

Instead of this, We can set actual host header in the nginx, if this the request is coming from an IP.

Credit goes to:

Leave a comment