What does Rails 3 session_store domain :all really do?

后端 未结 5 776
抹茶落季
抹茶落季 2020-11-28 19:09

Updated question to make it more clear

I understand that you can set the domain of your session_store to share sessions between subdomains like this

5条回答
  •  春和景丽
    2020-11-28 19:50

    I didn't think any of the existing answers directly answered the question in the title so I wanted to chip in.

    When the client (browser) goes to a website, the website tells the client to set a cookie. When it does so, it specifies the cookie name, value, domain, and path.

    :domain => :all tells Rails to put a dot in front of the cookie domain (which is whatever host your browser has browsed to), such that the cookie applies to all subdomains.

    Here is the relevant code from Rails 4.1 (actionpack/lib/action_dispatch/middleware/cookies.rb):

      def handle_options(options) #:nodoc:
        options[:path] ||= "/"
    
        if options[:domain] == :all
          # if there is a provided tld length then we use it otherwise default domain regexp
          domain_regexp = options[:tld_length] ? /([^.]+\.?){#{options[:tld_length]}}$/ : DOMAIN_REGEXP
    
          # if host is not ip and matches domain regexp
          # (ip confirms to domain regexp so we explicitly check for ip)
          options[:domain] = if (@host !~ /^[\d.]+$/) && (@host =~ domain_regexp)
            ".#{$&}"
          end
        elsif options[:domain].is_a? Array
          # if host matches one of the supplied domains without a dot in front of it
          options[:domain] = options[:domain].find {|domain| @host.include? domain.sub(/^\./, '') }
        end
      end
    

    I see you've already answered the second part of your question about allowing subdomains to have separate sessions.

提交回复
热议问题