Best way to handle virtual hosts in Django?

Hello everyone and thank you so much for bringing to life this forum!

I was wondering what’s the recommended approach for handling virtual hosts in Django. At the stage I’m in this project, the site framework is a bit overkill. Here’s what I did instead:

def check_domain(request):
    if not request.get_host() == SITE:
        raise PermissionDenied

and then in each view:

def index(request):
    # do stuff

This appoach prevents the user from reaching paths that are not associated with the correct host header. I know it’s a dirty hack, I’m thinking of a custom decorator or a mixin, but I was wondering if there is already some best practice I’m missing.

Thank you!

You can add a middleware that sets request.urlconf to route requests to an entirely different set of URL’s. I’ve used this technique a couple of times quite successfully.

See point #1 in

I was thinking about a middleware, but I was missing the link with urlconf. Thank you!

See also for tests:

Yeah I already have a test where the client calls the route with different HTTP_HOST values

Just saw your blog post on the topic. Thanks for covering it!

Sure! I love putting down things on my blog!