简体   繁体   中英

Using subdomains in django

Please tell me whether it is possible (if so, how) to use for pages each user subdomains. For example, now I have a URL of the form: http://hostname.com/user/1 I need to get http://username.hostname.com/

You have a number of options depending on how in-depth you want to go.

  1. One option is to handle the routing at the web server level. Basically you will capture the subdomain part of the URL and rewrite it to a different location within your server.

    For example http://username1.local.host/signin will be captured by your webserver and internally routed to a resource such as /username1/signin . The end user will subdomains but your code will handle url parts be none the wiser as to what has happened.

    Your urls.py will then handle this like any normal request.

     url_pattern = [ ... url(r'(?P<subdomain>[az]+)/sigin/$', 'view'), ]

    For Nginx you will need to look into "subdomain to subdirectory re-writing".

    I would personally use this option for what you have stated in your question. Whilst this method is a little more tricky to setup initially (keep at it until it works). It will be a lot easier to maintain and work with in the long run.

  2. The other option is to handle the subdomains at the django level using a package such as Django Subdomains (I have used this one in the past and found it to be my preferred option (in terms of handling subdomains within django code)). Without going into too much detail nginx will capture the subdomains and route all of it to django. Django will then handle the subdomains at the middleware level.

Personally I would use option 1 for your usage. Option 2 is if you want different apps on different domains for example: blog.local.host , support.local.host .

Consider using django-hosts

From docs:

# For example, if you own example.com but want to serve 
# specific content at api.example.com and beta.example.com, 
# add the following to a hosts.py file:

from django_hosts import patterns, host

host_patterns = patterns('path.to',
    host(r'api', 'api.urls', name='api'),
    host(r'beta', 'beta.urls', name='beta'),
)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM