Login

Serve multiple hostnames with different URLCONF's from one Django instance

Author:
rmt
Posted:
May 17, 2009
Language:
Python
Version:
1.0
Tags:
multiple urlconf multihost host
Score:
3 (after 3 ratings)

This works with Django 1.0.0 and later. It sets the request.urlconf variable to an alternate urlconf, if there's a match to the hostname in settings.MULTIHOST_URLCONF_MAP

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
# File: django_multihost.py
#
# A simple middleware component that lets you use a single Django
# instance to server multiple distinct hosts.
#
# Example usage (in settings.py):
#   MIDDLEWARE_CLASSES = (
#      ...,
#      'django_multihost.MultiHostMiddleware',
#   )
#   MULTIHOST_URLCONF_MAP = {
#     'domain1.com'     : 'app1.urls',
#     'domain1.com:8080': 'app1.urls',
#     'domain2.com'     : 'app2.urls',
#   }
#
# If a host wasn't found, settings.ROOT_URLCONF will be used.
#

from django.conf import settings
from django.utils.cache import patch_vary_headers
from django.core.exceptions import MiddlewareNotUsed

class MultiHostMiddleware:
    def __init__(self):
        if not hasattr(settings, 'MULTIHOST_URLCONF_MAP'):
            raise MiddlewareNotUsed

    def process_request(self, request):
        try:
            host = request.META["HTTP_HOST"]
            if host[-3:] == ":80":
                host = host[:-3] # ignore default port number, if present
            request.urlconf = settings.MULTIHOST_URLCONF_MAP[host]
        except KeyError:
            pass # use default urlconf (settings.ROOT_URLCONF)

    def process_response(self, request, response):
        if getattr(request, "urlconf", None):
            patch_vary_headers(response, ('Host',))
        return response

More like this

  1. Referer-checking view decorators by robbie 7 years, 10 months ago
  2. ScriptPrefixMiddleware by shellsage 5 years, 6 months ago
  3. Adding Fields to Registration Form [or Multiple Inheritance of forms] by simonkagwe 3 years, 5 months ago
  4. Making multi node / multi vhost easier! by sleepycal 3 years, 12 months ago
  5. Compact idiom for legacy URLs in URLconfs by pbx 7 years, 10 months ago

Comments

Please login first before commenting.