CodingBowl

How to Use django-hosts for Subdomain Routing in Django Projects

Published on 16 Jun 2025Server Hosting
image
Photo by John on Unsplash

django-hosts is a Django library that allows you to manage multiple subdomains within a single Django project by mapping each subdomain to its own URL configuration. This is useful for structuring apps like www.example.com, api.example.com, or admin.example.com using clean, maintainable code. In this guide, you'll learn how to install, configure, and test django-hosts in a Django project.

  1. Install django-hosts:
    pip install django-hosts
  2. Add django_hosts to INSTALLED_APPS in settings.py:
    INSTALLED_APPS = [
        # other apps
        'django_hosts',
    ]
  3. Add django-hosts middleware in settings.py:
    MIDDLEWARE = [
        'django_hosts.middleware.HostsRequestMiddleware',
        'django.middleware.security.SecurityMiddleware',
        'django.middleware.common.CommonMiddleware',
        # other middleware
        'django_hosts.middleware.HostsResponseMiddleware',
    ]
  4. Set ROOT_HOSTCONF and DEFAULT_HOST in settings.py:
    ROOT_HOSTCONF = 'your_project.hosts'
    DEFAULT_HOST = 'www'
  5. Create a hosts.py file in your project directory (next to settings.py):
    from django_hosts import patterns, host
    
    host_patterns = patterns('',
        host(r'www', 'your_project.urls', name='www'),
        host(r'api', 'your_project.api_urls', name='api'),
    )
  6. Ensure urls.py and api_urls.py exist for each subdomain you reference.
  7. Run the server and test your subdomains:
    • http://localhost:8000/ for www
    • http://api.localhost:8000/ for api (you may need to modify /etc/hosts)

Meow! AI Assistance Note

This post was created with the assistance of Gemini AI and ChatGPT.
It is shared for informational purposes only and is not intended to mislead, cause harm, or misrepresent facts. While efforts have been made to ensure accuracy, readers are encouraged to verify information independently. Portions of the content may not be entirely original.

image
Photo by Yibo Wei on Unsplash