Skip to content

Use Nginx as reversed proxy for WebSocket

WebSocket协议相比较于HTTP协议成功握手后可以多次进行通讯,直到连接被关闭。但是WebSocket中的握手和HTTP中的握手兼容, 它使用HTTP中的Upgrade协议头将连接从HTTP升级到WebSocket。


WebSocket工作在HTTP的80和443端口并使用前缀ws://或者wss://进行协议标注,在建立连接时使用HTTP/1.1的101状态码进行协议切换, 当前标准不支持两个客户端之间不借助HTTP直接建立Websocket连接。


NGINX从1.3版本开始支持WebSocket。

确认nginx版本

确保nginx版本大于1.3

nginx -v

增加ws配置

nginx配置文件http段增加以下内容,其中upstream是上游ws服务的地址

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

upstream websocket {
    server localhost:8282;
}
  • proxy_read_timeout: 语法 proxy_read_timeout time 默认值 60s 上下文 http server location 说明 该指令设置与代理服务器的读超时时间。它决定了nginx会等待多长时间来获得请求的响应。 这个时间不是获得整个response的时间,而是两次reading操作的时间。

  • proxy_send_timeout: 语法 proxy_send_timeout time 默认值 60s 上下文 http server location 说明 这个指定设置了发送请求给upstream服务器的超时时间。超时设置不是为了整个发送期间,而是在两次write操作期间。 如果超时后,upstream没有收到新的数据,nginx会关闭连接。

另外新增server配置

server {
    server_name YOUR_SERVER_NAME;
    listen 80;
    location / {
       proxy_pass http://websocket;
       proxy_read_timeout 300s;
       proxy_send_timeout 300s;
       proxy_http_version 1.1;
       proxy_set_header Upgrade $http_upgrade;
       proxy_set_header Connection $connection_upgrade;
    }    
}

重启nginx

nginx -t
nginx -s reload

参考资料

  • http://pankajmalhotra.com/Websockets-SSL-TLS-Termination-Using-NGINX-Proxy

Disclaimer
  1. License under CC BY-NC 4.0
  2. Copyright issue feedback me#imzye.me, replace # with @
  3. Not all the commands and scripts are tested in production environment, use at your own risk
  4. No privacy information is collected here
Try iOS App