The application allows a user to log in to either the main site ( or a user site ( Logging in creates a user session.

In its current form, the application maintains separate and independent user sessions for the main site and each subdomain. That’s because session data for each visitor is managed by browser-based cookies and cookies are not shared across domains (and, by default, not shared across subdomains). Not only is the user login not maintained between the main site and subdomains, but flash messages (used to communicate between actions) are lost because they are stored in sessions.

For the example application, we want a visitor to sign up on the main site but only log in on their subdomain-hosted site. As implemented, we don’t want sessions to be shared across subdomains.

However, your requirements may differ. If you wish to maintain sessions between the main site and subdomain-hosted sites, modify the configuration file to add the parameter :domain => :all:

If you are using subdomains and Devise you may encounter this problem in internet explorer:

Started GET "/" for at 2012-05-30 19:18:51 +1000
Processing by Users::DashboardController#home as HTML
Completed 401 Unauthorized in 1ms

You need to configure config/initializers/session_store.rb to share across subdomains, for example:

Rails.application.config.session_store :cookie_store, key: '_my_app_session', domain: ''

or if you want it works with any domain:

Rails.application.config.session_store :cookie_store, key: '_my_app_session', domain: :all, tld_length: 2
Rails.application.config.session_store :cookie_store, key: '_your_session', :domain => :all, :tld_length => 2, secure: true

The key config here is domain=all which creates cookies for all sub-domains. tld_length define the top level domain length. For example,, your tld_length will be 2. Finally, the secure config tells the browser to send cookies only for secure connection.


    :domain - cookie所属的域名,默认为nil
    :tld_length - 当domain设置为:all,这个参数可被使用,指定域名的长度,如,长度可设为1
    :expires - 失效时间,值为time对象
    :secure - 是否这个cookie只传送到HTTPS服务器。默认是false
    :httponly - 这个cookie是否只用于HTTP。默认值为false。

about domain tld_length

2.3.1 :018 > ActionDispatch::Http::URL.extract_domain('', 1)
 => ""
2.3.1 :016 > ActionDispatch::Http::URL.extract_domain('', 2)
 => ""
2.3.1 :017 > ActionDispatch::Http::URL.extract_domain('', 1)
 => ""

2.3.1 :015 > ActionDispatch::Http::URL.extract_domain('', 2)
 => ""


How To: Use subdomains · plataformatec/devise Wiki

Rails Tutorial for Subdomains with Devise · RailsApps

Configure rails app to share cookies across sub-domains – Calvin’s Engineering Logs

Sharing A Devise User Session Across Subdomains With Rails 3

ruby on rails中的session & cookies整理 – tompiking的博客 – CSDN博客

Share session (cookies) between subdomains in Rails? – Stack Overflow

session_storeでdomainとtld_lengthを設定した際、ChromeでlocalhostのCookieが保存されない – Qiita


Leave a Reply

Your email address will not be published. Required fields are marked *