Traefik, Django and ALLOWED_HOSTS
When setting up Django behind Traefik you want to make a few tweaks to cleanly handle the Django ALLOWED_HOSTS
setting.
Firstly you want to decide whether or not the Django application should be accessible directly by IP address, if so, make sure that the IP address is added to the ALLOWED_HOSTS
setting.
If not, then you want to have the Django application listening on localhost
and not the external IP address.
There are 2 ways for Traefik to handle checking the host headers;
Option 1:
The simplest way is to make use of the HostHeader rule in the router;
http:
routers:
router1:
rule: "HostHeader(`example.com`, `www.example.com`)"
service: myService
Option 2:
A more convoluted option is to make use of the Traefik allowedHosts middleware headers to allow only valid hosts.
A basic sample would be;
http:
routers:
router1:
rule: "Host(`example.com`, `www.example.com`)"
service: myService
middlewares:
- "myHosts"
middlewares:
myHosts:
headers:
allowedHosts:
- "example.com"
- "www.example.com"
And to ensure that it’s all working correctly;
# valid request
curl -H "HOST: example.com" http://example.com
# invalid HTTP_HOST header
curl -H "HOST: wrong.example.com" http://example.com