nginx(二)支持websocket配置

在默认的配置nginx.conf文件中做如下配置改动

一、http域的设置

http { 
  include mime.types;
  default_type application/octet-stream;

  #log_format main '$remote_addr - $remote_user [$time_local] "$request" '
  # '$status $body_bytes_sent "$http_referer" '
  # '"$http_user_agent" "$http_x_forwarded_for"';

  #access_log logs/access.log main;

  sendfile on;

  #add for websocket
  map $http_upgrade $connection_upgrade {
    default upgrade;
    '' close;
  }

upstream websocket {
  #ip_hash; //路由规则之一,顾名思义
  server localhost:8010; //真正提供websocket服务的服务器地址和端口
  server localhost:8080; //真正提供websocket服务的服务器地址和端口
}

二、server域的设置

server {
    listen 80; //外部应用访问的端口
  server_name 172.18.4.114; //外部应用访问的地址

  #charset koi8-r;

  #access_log logs/host.access.log main;

  location / { 
    proxy_pass http://websocket; //这个配置指向http域的配置
    proxy_read_timeout 300s; //websocket空闲保持时长

    proxy_set_header Host $host;
    proxy_set_header X-Real-IP $remote_addr;
    proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;

    proxy_http_version 1.1;
    proxy_set_header Upgrade $http_upgrade;
    proxy_set_header Connection $connection_upgrade;

    #root html;
    #index index.html index.htm;
  }

三、整体测试

1. 启动后端的websocket服务器,此例中是2个。

2. 打开浏览器访问http://172.18.4.114,发现链接建立到一个服务器上。

3. 再打开一个浏览器页签访问http://172.18.4.114,发现链接建立到另一个服务器上。

4. 分配成功。

5. 空闲超过5分钟后,会发现自动拆链。

原文地址:https://www.cnblogs.com/yoyotl/p/10419917.html