Share Session Cookies between Subdomains with Tomcat

Published on March 23, 2015 by

In order to share session cookies between subdomains in your Java web application hosted with Apache Tomcat, you need to make a simple configuration change. What you simply need to do is to make a small change to your web application’s context. You might have more than one context if you have more than one web application hosted by your Tomcat web server. In my case, I have installed Tomcat on OS X, and therefore I need to changeĀ /Library/Tomcat/conf/context.xml. Note that the path to your Tomcat installation may differ depending on how you installed Tomcat and which platform you are running Tomcat on.

Nevertheless, once you have found the appropriate context, then you need to add theĀ sessionCookieDomain attribute to the context’s root node. The value should be the domain name that you use to access your web application, prepended by a period.

<Context sessionCookieDomain="">
	<!-- ... -->

If you are not accessing your web application with a domain name, then you should add the below to your /etc/hosts file (for UNIX-based environments – the path is obviously different on Windows).

Now, save the file and restart Tomcat.

cd /path/to/tomcat/bin
./ stop
./ start

Your web application’s session cookies should now be shared across subdomains. Please note that the sessionCookieDomain attribute requires a Tomcat version of at least 6.0.27.

Now, in case you have more than one context (i.e. more than one web application), and you want to share session cookies between those as well, then you also have to set the sessionCookiePath to /, like so:

<Context sessionCookieDomain="" sessionCookiePath="/">
	<!-- ... -->

Thank you for reading.

Author avatar
Bo Andersen

About the Author

I am a back-end web developer with a passion for open source technologies. I have been a PHP developer for many years, and also have experience with Java and Spring Framework. I currently work full time as a lead developer. Apart from that, I also spend time on making online courses, so be sure to check those out!

3 comments on »Share Session Cookies between Subdomains with Tomcat«

  1. Q

    Hey Bo,

    Thanks a lot for sharing this. I used it to setup for my sub-domain based server on Tomcat 8.0.

    But seems for Tomcat 8.5, this setting no longer work (the leading dot “.” is no longer allowed. So far I failed to figure it out. Any idea please ?

  2. q

    so how to handle it ?

  3. Tony

    To still allow the leading dot (.), add the following inside your context.

Leave a Reply

Your e-mail address will not be published.