I know this question is old, but since Google brought me here I'll add these links
This answer touches on (A) authentication across subdomains and (B) detecting which subdomain is in use to potentially redirect the user
A.1. If you want to allow all (wildcard) subdomains
*.myapp.com, this is achieved by adding one line to settings.py:
SESSION_COOKIE_DOMAIN=".myapp.com"
Detailed here (SO, 2009), here (SO, 2010) and in Django docs
Note: login now won't work on localhost, so you have two choices if
you need to log in and out on localhost:
1: comment out that line in settings.py, or
2: amend your /etc/hosts file to include the following:
127.0.0.1 localhost
127.0.0.1 dev.myapp.com
Now you can visit dev.myapp.com
in your browser, and it'll actually be talking to 127.0.0.1, not your live
website. (Now, across dev.myapp.com
, site1.myapp.com
,
site2.myapp.com
and myapp.com
, if you log in/out of one, you'll be
logged in/out of them all.)
A.2. If you want to allow cross-authentication between just those two subdomains, i.e., they won't be logged into site3.myapp.com
, then it gets a bit more complicated
B. To view the subdomain being used
There are fancier packages to manage subdomains in django, but you could just look crudely at request.META['HTTP_HOST']:
try:
http_host = request.META['HTTP_HOST']
# alternative: http_host = request.get_host()
except KeyError:
http_host = None
print "Can't find HTTP_HOST"
if http_host and '.myapp.com' in http_host:
subdomain = http_host.split('.myapp.com')[0]
else:
subdomain = ''
Then check if you're happy with the request.user
using this subdomain
.
Use something like HttpResponseRedirect
to send them to a different subdomain if you like. If you've done A.1 or A.2 above, in your app's eyes, they're the same user (already logged in) in the new subdomain.myapp.com after being redirected (they don't have to log in again).
Example: if a user creates an account with ireland.myapp.com and you want to keep them always on that site, then when they try to visit usa.myapp.com, they'll still be logged in, you can identify them and send them back to ireland.myapp.com (fictitious example, not a metaphor for immigration!)