Django Sites Framework: Managing Multi-Domain Content with SITE_ID and Nginx
Django's built-in django.contrib.sites framework allows a single PostgreSQL database and codebase to power multiple distinct websites—associating articles, users, and configurations with one or more Site records via ForeignKey or ManyToManyField.
1. Dynamic Site Resolution Without Multiple Settings Files
While the traditional approach uses separate settings_site1.py and settings_site2.py files with hard-coded SITE_ID constants, modern containerized deployments on Google Cloud Run or Kubernetes benefit from resolving the active Site dynamically via get_current_site(request):
from django.contrib.sites.shortcuts import get_current_site
from blog.models import Article
def site_articles_view(request):
current_site = get_current_site(request)
articles = Article.objects.filter(sites=current_site, published=True)
return render(request, "blog/list.html", {"articles": articles, "site": current_site})
2. Nginx Reverse Proxy Headers
Ensure Nginx or your Cloud Load Balancer forwards the exact host and scheme so Django resolves the right Site.domain and generates canonical HTTPS URLs:
proxy_set_header Host $host;
proxy_set_header X-Forwarded-Proto $scheme;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;