Ytech Python
Ytech Python

Reputation: 93

Dynamic Allowed Host in Django

I'm developing multitenant application using django. Every things works fine. But in the case of ALLOWED_HOST , I've little bit confusion, that how to manage dynamic domain name. I know i can use * for any numbers for domain, But i didn't wan't to use * in allowed host.

Here is my question is there any way to manage allowed host dynamically.

Upvotes: 3

Views: 2581

Answers (2)

Sanil Khurana
Sanil Khurana

Reputation: 1169

According to the Django doc,

Values in this list can be fully qualified names (e.g. 'www.example.com'), in which case they will be matched against the request’s Host header exactly (case-insensitive, not including port). A value beginning with a period can be used as a subdomain wildcard: '.example.com' will match example.com, www.example.com, and any other subdomain of example.com. A value of '*' will match anything; in this case you are responsible to provide your own validation of the Host header (perhaps in a middleware; if so this middleware must be listed first in MIDDLEWARE).

So, if you want to match a certain subdomain, you can use the subdomain wildcard as explained above. If you want a different validation, as the documentation says, the right way to do it would be to allow all hosts and write your own middleware.

If you don't know about middlewares, they are a simple mechanism to add functionality when certain events occur. For example, you can create a middleware function that executes whenever you get a request. This would be the right place for you to put your Host validation. You can get the host using the request object. Refer to the official docs on middleware if you want to know more.

A simple middleware class for your problem could look something like -

import requests
from django.http import HttpResponse

class HostValidationMiddleware(object):
    def process_view(self, request, view_func, *args, **kwargs):
        host = request.get_host()
        is_host_valid = # Perform host validation
        if is_host_valid:
           # Django will continue as usual
           return None
        else:
           response = HttpResponse
           response.status_code = 403
           return response

If you need more information, comment below and I will try to help.

Upvotes: 5

bubthegreat
bubthegreat

Reputation: 301

The setting should be loaded once on startup - generally those settings don't change in a production server setup. You can allow multiple hosts, or allow multiple subdomains.

*.example.com would work, or you can pass a list of domains if I remember correctly.

Upvotes: 0

Related Questions