Skip to content

Instantly share code, notes, and snippets.

@mieko
Last active March 4, 2016 09:39
Show Gist options
  • Save mieko/893617c30dd06ed6ecc3 to your computer and use it in GitHub Desktop.
Save mieko/893617c30dd06ed6ecc3 to your computer and use it in GitHub Desktop.
Using nginx to allow ActionCable within the same host

This is an example of how to configure nginx to allow ActionCable WebSocket connections to use the same host as your primary site. For example, instead of cable.myapp.dev, you can use myapp.dev/_c/.

In my case, we have a multi-tenanted environment, e.g., bob.myapp.dev and jim.myapp.dev. This lets the ActionCable connection still use the Host: header to select a tenant, and use normal cookies for user identification. wss://bob.myapp.dev/_c/ is authorized as normal. It also piggybacks off of whatever TLS setup is available.

@App ?= {}
websocket_uri = ->
prot = if location.protocol == 'https:' then 'wss:' else 'ws:'
"#{prot}//#{location.host}/_c/"
App.cable = Cable.createConsumer(websocket_uri())
upstream myapp_cable {
# Set this to your pool of upstream ActionCable servers
server localhost:28080;
}
server {
server_name .myapp.dev;
# Normal stuff goes here...
# This will give us the URL myapp.dev/_c/ for cable connections
location /_c/ {
proxy_pass http://myapp_cable/;
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection "upgrade";
proxy_set_header Host $http_host;
break;
}
}
@kelso
Copy link

kelso commented Mar 4, 2016

Thank you.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment