Splitting Django project across subdomains

2019-03-01 00:23发布

问题:

I'm currently developing a site where the functionality needs to be split into separate subdomains, dashboard.example.com, admin.example.com, and facebook.example.com. I would like everything to be served through a single Django project because everything will be using the same core models. I'm using Nginx as a front-facing proxy server handling static files and passing all other requests to Apache.

The solution I thought of was to map each of these subdomains to the appropriate app through nginx:

server {
    listen 80;
    server_name dashboard.example.com;
    ...

    location / {
        proxy_pass http://127.0.0.1/dashboard/;
        ...
    }
}

server {
    listen 80;
    server_name admin.example.com;
    ...

    location / {
        proxy_pass http://127.0.0.1/admin/;
        ...
    }
}

...doing that for each subdomain, effectively mapping the subdomains to their respective app url namespaces. The problem I encountered was that Django was unaware of the mapping, so when it reversed a URL, it would prepend /dashboard/, etc. to it, creating URLs like dashboard.example.com/dashboard/dashboard/. I figure I could write a custom reverse function to strip out the unnecessary subdirectory, but that seems like a band-aid.

Is there a better way to accomplish what I need, or should I restructure the project?

Thanks for your help.

回答1:

Django's Sites framework (https://docs.djangoproject.com/en/1.7/ref/contrib/sites/) should be sufficient for this, if not, take a look at django-subdomains (http://django-subdomains.readthedocs.org/en/latest/) as seems to have a means of resolving your reverse URLs (based off a quick Google search, I've never used it myself!)