简体   繁体   English

适用于Amazon ELB的Django ALLOWED_HOSTS

[英]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: 我正在使用Django,并且具有ALLOWED_HOSTS设置,以按如下方式包含EC2的私有IP:

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. 问题是上述内容没有考虑将请求转发到我的EC2实例的ELB Is there a way to make that work programmatically? 有没有办法以编程方式使其工作? Can I request the public IP address or have setting to check the DNS instead? 我可以请求公共IP地址还是可以设置检查DNS?

I'm seeing this issue with the ELB's public IP address. 我看到ELB的公共IP地址存在此问题。

Another simple solution would be to write a custom MIDDLEWARE which will give the response to ELB before the ALLOWED_HOSTS is checked. 另一个简单的解决方案是编写一个自定义MIDDLEWARE ,它将在检查ALLOWED_HOSTS之前将响应提供给ELB。 So now you don't have to load ALLOWED_HOSTS dynamically. 因此,现在您不必动态加载ALLOWED_HOSTS

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/ Django中间件参考https://docs.djangoproject.com/en/dev/topics/http/middleware/

Fetching AWS internal IPs and adding to the ALLOWED_HOST is not the best solution. 提取AWS内部IP并添加到ALLOWED_HOST并不是最佳解决方案。 Since this Fetching will happen only on application reload. 由于此提取仅在重新加载应用程序时发生。 ELB IPs can change anytime. ELB IP可以随时更改。

Instead of this, We can set actual host header in the nginx, if this the request is coming from an IP. 取而代之的是,如果请求来自IP,我们可以在nginx中设置实际的主机头。

Credit goes to: https://www.xormedia.com/django-allowed-hosts-and-amazon-elastic-load-balancer/ 信誉归功于: https : //www.xormedia.com/django-allowed-hosts-and-amazon-elastic-load-balancer/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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