Note: 基本的 WebSocket 的 Nginx 配置

745 查看

觉得很容易用到.. Nginx 从 1.3 开始支持 WebSocket, 现在已经是 1.4.4 了
相对 HTTP, 看过例子发现配置其实比较简单,

先用 ws 模块写一个简单的 WebSocket 服务器:

Server = require('ws').Server

wss = new Server port: 3000

wss.on 'connection', (ws) ->
  console.log 'a connection'
  ws.send 'started'

console.log 'server started'

然后修改 Hosts, 添加, 比如 ws.repo, 指向 127.0.0.1
然后是 Nginx 配置:

server {
  listen 80;
  server_name ws.repo;

  location / {
    proxy_pass http://127.0.0.1:3000/;
    proxy_redirect off;

    proxy_http_version 1.1;
    proxy_set_header Upgrade $http_upgrade;
    proxy_set_header Connection "upgrade";
  }
}

Reload Nginx 然后从浏览器控制台尝试链接, OK

new WebSocket('ws://ws.repo/')

或者通过 Upstream 的写法:

upstream ws_server {
  server 127.0.0.1:3000;
}

server {
  listen 80;
  server_name ws.repo;

  location / {
    proxy_pass http://ws_server/;
    proxy_redirect off;

    proxy_http_version 1.1;
    proxy_set_header Upgrade $http_upgrade;
    proxy_set_header Connection "upgrade";
  }
}

WebSocket 先是通过 HTTP 建立连接,
然后通过 101 状态码, 表示切换协议,, 在配置里是 Upgrade
不清楚具体里边发生了什么... 求指点...

具体 HTTP Header 上的参数参考 SegmengFault 上的文章:
http://segmentfault.com/a/1190000000382788

参考的相关文章:
nginx and WebSockets
WebSocket connection failed with nginx, nodejs and socket.io
Proxying WebSockets with Nginx
zhangkaitao/websocket-protocol
细说WebSocket - Node篇


返回博客首页: http://blog.tiye.me