Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

django multiple domains, single app

Tags:

django

I am trying to set my Django app work with multiple domains (while serving slightly different content) I wrote this middleware:

class MultiSiteMiddleware(object):
    def process_request(self, request):
        host = request.get_host()
        host_part = host.split(':')[0].split('.com')[0].split('.')
        host = host_part[len(host_part)-1] + '.com'
        site = Site.objects.get(domain=host)
        settings.SITE_ID = site.id
        settings.CURRENT_HOST = host
        Site.objects.clear_cache()
        return

In views I use this:

def get_site(request):
    current_site = get_current_site(request)
    return current_site.name

def view(request, pk):
    site = get_site(request)

    if site == 'site1':
        # serve content1
        ...
    elif site == 'site2'
        # serve content2
        ...

But now there are 404 errors (I sometimes find them in logs, don't see them while browsing my site manually) where they aren't supposed to be, like my site sometimes is serving content for wrong domains, can they happen because of some flaw in the above middleware and view code or I should look somewhere else?

like image 850
Bob Avatar asked Sep 05 '14 08:09

Bob


People also ask

Can I connect 2 domains for one website?

With most registrars, it's easy to forward multiple domains to your website so you can simply create one site and then redirect visitors who type one of your other domain names to that one website.

Is it good to have exposure in multiple domains?

Get more exposure.By owning more domains, your products, services and company will get more exposure to your target audience. Search engines will rank your site based on how many times certain keywords appear.

What is Django contrib sites?

contrib.sites is installed and returns either the current Site object or a RequestSite object based on the request. It looks up the current site based on request. get_host() if the SITE_ID setting is not defined. Both a domain and a port may be returned by request.


1 Answers

I had a similar requirement and decided not to use the django sites framework. My middleware looks like

class MultiSiteMiddleware(object):

    def process_request(self, request):
        try:
            domain = request.get_host().split(":")[0]
            request.site = Site.objects.get(domain=domain)
        except Site.DoesNotExist:
            return http.HttpResponseNotFound()

then my views have access to request.site

If you're seeing 404's for sites that aren't yours in your logs it would seem like somebody has pointed their domain at your servers IP address, you could use apache/nginx to filter these out before they hit your app, but your middleware should catch them (though possibly by raising an uncaught 500 error instead of a 404)

like image 182
Stuart Leigh Avatar answered Sep 28 '22 06:09

Stuart Leigh