How do I set Django ALLOW_HOSTS
on Elastic Beanstalk instance to allow Elastic Load Balancer IP?
Background
I deployed a Django website on Elastic Beanstalk. The website domain is added to ALLOW_HOSTS
so normal requests are accepted by Django correctly.
ALLOWED_HOSTS = ['.mydomain.com']
Elastic Load balancer visit Elastic beanstalk instances directly with IP address for health check, so next line allow the health check:
# add Elastic Beanstalk instance local IP
aws_ip = requests.get('http://169.254.169.254/latest/meta-data/local-ipv4', timeout=0.1).text
ALLOWED_HOSTS.append(aws_ip)
But I still got invalid HOST IP errors that seems Elastic Beanstalk instances are visited with Elastic load balancer public IP. There are solutions online for EC2 deployments as you can set HTTPD softwares to set http HOST header when it's visited by IP directly. But we cannot config Apache on Elastic Beanstalk.
How do I add the Elastic load balancer IP to the ALLOW_HOSTS
?
I believe the best approach would be to configure Apache to handle request host validation. Even with beanstalk you should be able to configure Apache using .ebextensions
.
The general idea is to check incoming requests for the 'ELB-HealthChecker/1.0'
User-Agent
and the health check URL you set as the request's REQUEST_URI
. Those requests can have their host header changed to an allowed host with the RequestHeader set Host
command.
If really don't want to configure Apache, you could implement a custom middleware to override Django's CommonMiddleware
to allow the health checker requests to bypass Django's ALLOWED_HOST
validation.
I went into greater detail in this answer if you need more on implementing one of these solutions.