我将一个Django应用程序部署到AWS Elastic Beanstalk,即使我已将其添加到允许的主机设置中,我也会收到“无效的HTTP_HOST标头”错误。
我收到这个错误:
Invalid HTTP_HOST header: 'recordings-env.kf4qfzaijd.us-west-2.elasticbeanstalk.com'. You may need to add 'recordings-env.kf4qfzaijd.us-west-2.elasticbeanstalk.com' to ALLOWED_HOSTS.
这就是我在settings.py中的内容
settings.py
:
ALLOWED_HOSTS = [
'127.0.0.1',
'localhost',
'.amazonaws.com',
'.elasticbeanstalk.com',
'recordings-env.kf4qfzaijd.us-west-2.elasticbeanstalk.com',
]
我认为问题是我的设置没有更新,因为如果我放ALLOWED_HOSTS = ['*']
也无法正常工作。我离开了DEBUG = True
并在请求信息中得到:ALLOWED_HOSTS: ['localhost']
在修改它之后,我运行eb deploy而没有错误。
这有点棘手,因为你需要用EB动态声明你的ALLOWED_HOSTS。这个article在Gotcha#3中提供了一些关于如何实现这一目标的好信息
我会创建一个名为settings_production.py
的单独设置文件,然后您可以在其中放置以下代码:
mysite的/ settings_production.py
from mysite.settings import *
def is_ec2_linux():
"""Detect if we are running on an EC2 Linux Instance
See http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/identify_ec2_instances.html
"""
if os.path.isfile("/sys/hypervisor/uuid"):
with open("/sys/hypervisor/uuid") as f:
uuid = f.read()
return uuid.startswith("ec2")
return False
def get_linux_ec2_private_ip():
"""Get the private IP Address of the machine if running on an EC2 linux server"""
from urllib.request import urlopen
if not is_ec2_linux():
return None
try:
response = urlopen('http://169.254.169.254/latest/meta-data/local-ipv4')
return response.read().decode("utf-8")
except:
return None
finally:
if response:
response.close()
# ElasticBeanstalk healthcheck sends requests with host header = internal ip
# So we detect if we are in elastic beanstalk,
# and add the instances private ip address
private_ip = get_linux_ec2_private_ip()
if private_ip:
ALLOWED_HOSTS += [private_ip, 'your-django-env.elasticbeanstalk.com']
# Other production overrides
DEBUG = False
现在您将“DJANGO_SETTINGS_MODULE”env变量设置为mysite.production_settings
用于您的生产(.i.e您的EB环境)。
更新:
我决定采取这个测试旋转,并设法让它运行起来。我发现了一些东西。上面的代码将每个实例的内部IP添加到ALLOWED_HOSTS
。这纯粹用于运行状况检查,以便AWS控制台可以在内部ping实例并接收200OK响应。我将离开上述解决方案,因为它仍然可用于此目的。但它不会解决您的特定错误。为您服务只需添加您的EB网址即可。您可以在AWS控制台(以红色突出显示)或cli中找到它,方法是输入eb status
并检查CNAME
属性。
配置:
以下是我在源代码中手动创建的基本配置文件:
.ebextensions / django.config
option_settings:
aws:elasticbeanstalk:container:python:
WSGIPath: mysite/wsgi.py
aws:elasticbeanstalk:application:environment:
DJANGO_SETTINGS_MODULE: mysite.settings_production
.ebextensions / DB-migrate.config
container_commands:
01_migrate:
command: "django-admin.py migrate"
leader_only: true
option_settings:
aws:elasticbeanstalk:application:environment:
DJANGO_SETTINGS_MODULE: mysite.settings_production
我已经意识到我的更改没有被部署,因为我需要先提交并且我不知道(我第一次部署到eb)。那就是问题所在。