How to maintain user session across sub domains in Django

Nowadays, people are using wildcard domains to provide same user experience across different domains. Using subdomains, we can be able to host multiple sites with the same domain name with the same code in a less time.

To enable wildcard subdomains for your site, you should add CNAME record like.

*.testsite.com CNAME YOUR_IP_ADDRESS

With this, you can be able to access your site domain with abc.testsite.com, xyz.testsite.com, etc.

After enabling wildcard domains, you should update your nginx file to accept wildcard domain requests.

server {

    listen       YOUR_IP_ADDRESS;

    server_name  testsite.com, *.testsite.com;

...

}

With the above nginx settings, you're able to access requests from wildcard domains like normal domain.

Now you've different wildcard domains for your site(testsite.com). When user login into testsite.com, redirects to the wildcard domain(abc.testsite.com) we should maintain same user session across subdomains. By default, django application isn't maintaining same user session across subdomains. To maintain this, we should add following details to the application settings file.

    SESSION_COOKIE_DOMAIN = ".testsite.com"

    DOMAIN_NAME = "testsite.com"

Here SESSION_COOKIE_DOMAIN should start with '.' character followed by DOMAIN_NAME. This will handle and enable user session/cookies across wildcard domains(abc.testsite.com, xyz.testsite.com, testsite.com)

Note:

In local development, your domain should start .com or .io update your localhost with any other domains in /etc/hosts file:

    127.0.0.1       testsite.io

    127.0.0.1       abc.testsite.io

And your settings file should be

    SESSION_COOKIE_DOMAIN = ".testsite.io"

    DOMAIN_NAME = "testsite.io"

With the above settings, django application will maintain user session across subdomains.

Posted On 04 June 2019 By MicroPyramid


Need any Help in your Project?Let's Talk

Latest Comments

Subscribe To our news letter

Subscribe and Stay Updated about our Webinars, news and articles on Django, Python, Machine Learning, Amazon Web Services, DevOps, Salesforce, ReactJS, AngularJS, React Native.
* We don't provide your email contact details to any third parties