Configure Allowed Hosts

A snippet showing how to configure ALLOWED_HOSTS in settings.


# settings.py

import os

# Default to localhost for safety
_raw_hosts = os.environ.get("DJANGO_ALLOWED_HOSTS", "localhost,127.0.0.1")
ALLOWED_HOSTS = [h.strip() for h in _raw_hosts.split(",") if h.strip()]
  

# Linux/macOS
export DJANGO_ALLOWED_HOSTS="example.com,www.example.com"

# Windows PowerShell
$env:DJANGO_ALLOWED_HOSTS="example.com,www.example.com"

# Runserver with env var
DJANGO_ALLOWED_HOSTS="localhost,127.0.0.1" python manage.py runserver
  
Explanation:
  • ALLOWED_HOSTS prevents HTTP Host header attacks by whitelisting valid domains.
  • Always set this in production - leaving it empty ([]) will block all requests.
  • Use environment variables for flexible per-environment configuration.
  • Include both bare and www. domains if you want to serve both.
  • Category Deployment & Settings
  • Total Views 1266
  • Last Modified 16 November, 2025
  • Tags #settings #allowed hosts #security #deployment
Never miss a story on Django.wiki

Subscribe for fresh tutorials, snippets, and updates.

By subscribing you agree to our Privacy Policy.