NeverBe
NeverBe

Reputation: 5038

Websockets with the main application (nginx + passenger + faye)

I'm trying to setup websockets on my rails application. My application works with iOS client that uses SocketRocker library.

As websockets backend i use faye-rails gem. It is integrated to the rails app as rack middleware

config.middleware.delete Rack::Lock
config.middleware.use FayeRails::Middleware, mount: '/ws', server: 'passenger', engine: {type: Faye::Redis, uri: redis_uri}, :timeout => 25 do
  map default: :block
end

It works perfect until i upload it to the production server with Nginx. I have tried a lot of solutions to pass websocket request to the backend, but with no luck. The main thing is there are two servers running, but i have just one. My idea was i just needed to proxify requests from /faye endpoint to /ws (to update headers). What is correct proxy_pass parameters should be in my case?

    location /faye {
    proxy_pass http://$server_name/ws;
    proxy_buffering off;
    proxy_http_version 1.1;
    proxy_set_header Upgrade $http_upgrade;
    proxy_set_header Connection "upgrade";
    }

Upvotes: 2

Views: 911

Answers (1)

Fernando Vieira
Fernando Vieira

Reputation: 3333

I had a similar problem and after struggling for a while, I finally could make it work.

I'm using nginx 1.8 with thin server with gem 'faye-rails' and my mount point is /faye

My nginx config looked like this:

upstream thin_server {
    server 127.0.0.1:3000;
}

map $http_upgrade $connection_upgrade {
        default upgrade;
        ''      close;
}

server {
    ...   
    proxy_redirect off; 
    proxy_cache off;     

    location = /faye {
        proxy_pass http://thin_server;
        proxy_http_version 1.1;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection $connection_upgrade;
        chunked_transfer_encoding off;
        proxy_buffering off;
        proxy_cache off;
    }

    location / {
        try_files $uri/index.html $uri.html $uri @proxy;
    }

    location @proxy {
        proxy_pass http://thin_server;
        proxy_set_header  X-Real-IP  $remote_addr;                      
        proxy_set_header  X-Forwarded-For $proxy_add_x_forwarded_for;   
        proxy_set_header  Host $http_host;                              
    }                                                            
    ...
}                                                  

The final turn point for me to make it work was when I set the "location = /faye". Before I tried "location /faye" and "location ~ /faye" and it failed. It looks like the equal sign "=" prevents nginx to mix with other location settings.

Upvotes: 1

Related Questions