在默認的配置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分鍾后,會發現自動拆鏈。