Julien
Julien

Reputation: 2319

Nginx + 1 Rails app + Multiple Domains + 1 session

Here's my situation, I have a Rails 4 app that can be accessed by multiple domains, depending on the domain, the content changes.

Say the main domain is domain1 and all the other domains just use Nginx's proxy_pass to forward the requests to domain1, this is all working fine except that when a user logs in domain2, rails sets the session for domain1 so the user in domain2 remains logged out because the session is not set for domain2.

I understand cookies can't be shared across different domains, but since it's the same app handling all those domains, surely something should be possible.

Any ideas?

UPDATE

Here's where I'm at:

Yet I am unable to set a session from domain2, what am i missing here?

CODE

Middleware

class ProxyPassCookie

    def initialize app
        @app = app
    end

    def call env
        host = env["HTTP_HOST"].split(':').first

        #rack attaches HTTP_ to all headers
        dom = env["HTTP_WLDOMAIN"].blank? ? host : env["HTTP_WLDOMAIN"]
        env["rack.session.options"][:domain] = ".#{dom}"
        @app.call(env)
    end

end

config/initializers/session_store.rb

Rails.application.config.session_store :cookie_store, key: '_myapp_session', :domain => :all

config/environments/development.rb | production.rb

config.middleware.use "ProxyPassCookie"

There's got to be a way to do this, any input appreciated!

Upvotes: 0

Views: 223

Answers (1)

Julien
Julien

Reputation: 2319

Finally solved this, all my Rails stuff was fine, the problem was in the Nginx configs, more specifically that the main domain was using SSL while the others weren't so i guess Nginx was not setting the cookies for security reasons.

Upvotes: 1

Related Questions