In a django web application, how do you give users their own subdomain?

我的梦境 提交于 2019-11-28 13:41:56

问题


I'm starting a new web app project using Django and Pinax. I want to be able to give my users unique domain names like Wordpress and other sites do : username.wordpress.com. I'm not sure how to approach this with Django, since the url parsing logic (in urls.py) starts with the url AFTER the domain name.

More specifically, there will be multiple groups of users, each group having a unique name. Not sure that makes a difference, but I thought I should mention that.

Is there some way I can manipulate the http request so that the URL looks to Django as if the url were something like www.domain.com/groupname, but still showed in the browser address bar as groupname.domain.com?


回答1:


You can use some custom middleware to intercept the request and get the subdomain from it. The following code will retrieve the subdomain and redirect to a view by reversing the named url.

Put it in a middleware.py file in your app.

Make sure you set up the middleware in your settings.py file.

Make sure you've named your view in urls.py

middleware.py

from django.http import HttpResponseRedirect
from django.core.urlresolvers import reverse
import re

subdomain_pattern = re.compile('(?P<subdomain>.*?)\..*?')

class SubdomainMiddleware(object):
    def process_request(self, request):
        match = subdomain_pattern.match(request.get_host())
        subdomain = match.group('subdomain')
        redirect_url = reverse('groups_detail', args=[subdomain])
        return HttpResponseRedirect(redirect_url)

urls.py

from django.conf.urls.defaults import *

urlpatterns = patterns('',
    url(r'^groups/(?P<name>.+)/$', 'groups.views.detail', {}, name='group_detail'),
)

Note: this code is untested.

Redirecting can alter the URL's appearance. If you want to avoid this, simply call the associated view, capture its result, and return it in an HttpResponse().




回答2:


You need to handle this via your webserver. If you have Django urls like...

/users/<username>/

... then use rewrite rules in the webserver to map <username>.domain.com to domain.com/users/<username>/.

If you're using Apache, you can read up here. Otherwise, each webserver has their own conventions but all will support the notion of url rewrites.




回答3:


See this other alternative configuring the appserver



来源:https://stackoverflow.com/questions/624827/in-a-django-web-application-how-do-you-give-users-their-own-subdomain

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!