Django ALLOWED_HOSTS for Amazon ELB

前端 未结 2 2113
暖寄归人
暖寄归人 2021-02-20 07:03

I\'m using Django and I have the ALLOWED_HOSTS setting to include my EC2\'s private IP as per below:

import requests
EC2_PRIVATE_IP = N         


        
相关标签:
2条回答
  • 2021-02-20 07:54

    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:

    project/app/middleware.py

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

    settings.py

    MIDDLEWARE = [
        'corsheaders.middleware.CorsMiddleware',
        'app.middleware.HealthCheckMiddleware',
        'django.middleware.security.SecurityMiddleware',
        'django.contrib.sessions.middleware.SessionMiddleware',
        'django.middleware.common.CommonMiddleware',
        'django.middleware.csrf.CsrfViewMiddleware',
        ...
    ]
    

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

    0 讨论(0)
  • 2021-02-20 07:57

    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: https://www.xormedia.com/django-allowed-hosts-and-amazon-elastic-load-balancer/

    0 讨论(0)
提交回复
热议问题