简体   繁体   中英

Django ALLOWED_HOSTS for Amazon ELB

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 = None
try:
    EC2_PRIVATE_IP = requests.get('http://169.254.169.254/latest/meta-data/local-ipv4', timeout=0.01).text
except requests.exceptions.RequestException:
    pass
if EC2_PRIVATE_IP and not DEBUG:
    ALLOWED_HOSTS.append(EC2_PRIVATE_IP)

Problem is that the above does not take into consideration the ELB 's that forward the request to my EC2 instances. Is there a way to make that work programmatically? Can I request the public IP address or have setting to check the DNS instead?

I'm seeing this issue with the ELB's public IP address.

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/

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/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM