~/aglili

Django 101: Sub Domain Based Routing

Published: 1/6/2026 (Updated: 1/6/2026)

Sub Domain Based Routing

In this short blog post we will be looking at how to route requests to our django application based on their subdomain. Lets say we had a top level domain which pointed to our django application for school management eg: www.joyschools.edu. A need might arise where we want to routes users to certain applications within our django app based on subdomains they hit. For example teachers.joyschools.edu or students.joyschools.edu. This way theres a clear seperation and also we also get to use one application to serve all these use cases.

lets begin

  • Install the django-hosts package
pip install django-hosts || uv add django-hosts
  • Configure your applications settings.py file
# add the django hosts to your Installed Applications
INSTALLED_APPS += ["django_hosts"]

# add the django-hosts middleware to your middlewares
MIDDLEWARE = [
    "django_hosts.middleware.HostsRequestMiddleware", #add here
    'django.middleware.security.SecurityMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
]

# add routing configuration 
ROOT_HOSTCONF = "core.hosts" #where `core` is your main project directory
DEFAULT_HOST = "www"

create a hosts.py in the main project directory and configure the application routing

from django_hosts import patterns, host



host_patterns = patterns(
    "",
    host(r"www","core.urls",name="www"), #main project urls
    host(r"teachers","teachers.urls",name="teacher") #pointing this towards the teachers app url config,
    host(r"students","students.urls",name="student") #pointing this towards the students app url config,
)

Now you have configured the routing. In local development you can visit

http://students.localhost:8000 || http://teachers.localhost:8000/

to visit the students application and teachers applications

In production. youll have to create dns records for students.joyschools.edu and teachers.joyschools.edu and point them to your server for this to work .

Thank You