适用于Amazon ELB的Django ALLOWED_HOSTS [英] Django ALLOWED_HOSTS for Amazon ELB
问题描述
我使用的是Django,并且我具有ALLOWED_HOSTS
设置,其中包括我的EC2
的私有IP,如下所示:
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)
问题是上述内容未考虑将请求转发到我的EC2
实例的ELB
.有没有办法以编程方式使其工作?我可以请求公共IP地址还是可以设置检查DNS?
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?
我看到了ELB的公共IP地址的问题.
I'm seeing this issue with the ELB's public IP address.
推荐答案
另一个简单的解决方案是编写自定义MIDDLEWARE
,它将在检查ALLOWED_HOSTS
之前将响应发送给ELB.因此,现在您不必动态加载ALLOWED_HOSTS
.
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.
中间件可以很简单:
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中间件参考 https://docs.djangoproject.com/en/dev/topics/http/middleware/
Django Middleware reference https://docs.djangoproject.com/en/dev/topics/http/middleware/
这篇关于适用于Amazon ELB的Django ALLOWED_HOSTS的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!