ALLOWED_HOSTS setting?The ALLOWED_HOSTS setting is a security measure in Django. It tells Django which host/domain names it can serve. This helps prevent attackers from sending requests with fake Host headers.
ALLOWED_HOSTS = [], what will happen when a user tries to access the site?When ALLOWED_HOSTS is empty, Django will not allow any host headers and will raise a DisallowedHost error for all incoming requests. This prevents serving the app on unknown domains.
ALLOWED_HOSTS to allow requests from example.com and localhost.ALLOWED_HOSTS must be a list of strings. Option A correctly uses a list. Option A is a string, C is a set, and D is a tuple, which Django does not accept.
ALLOWED_HOSTS = ['.example.com'], why might requests to example.com itself cause a DisallowedHost error?ALLOWED_HOSTS = ['.example.com']A leading dot in ALLOWED_HOSTS means allow all subdomains of that domain, but not the domain itself. So '.example.com' allows 'www.example.com' but not 'example.com'.
ALLOWED_HOSTS = ['example.com', '.mysite.org']
hosts_to_test = ['example.com', 'www.mysite.org', 'mysite.org', 'evil.com']
results = []
for host in hosts_to_test:
try:
from django.http.request import validate_host
validate_host(host, ALLOWED_HOSTS)
results.append(f"{host}: allowed")
except Exception:
results.append(f"{host}: disallowed")
print(results)What will be printed?
ALLOWED_HOSTS = ['example.com', '.mysite.org'] hosts_to_test = ['example.com', 'www.mysite.org', 'mysite.org', 'evil.com'] results = [] for host in hosts_to_test: try: from django.http.request import validate_host validate_host(host, ALLOWED_HOSTS) results.append(f"{host}: allowed") except Exception: results.append(f"{host}: disallowed") print(results)
The validate_host function checks if the host matches any entry in ALLOWED_HOSTS. 'example.com' matches exactly. 'www.mysite.org' matches the '.mysite.org' wildcard. 'mysite.org' does not match '.mysite.org' because the leading dot only allows subdomains, not the root domain. 'evil.com' is not allowed.