Nginx配置Websocket反向代理

websocket服务使用 spring-boot-starter-websocket 来开发的

# websocket message服务
upstream websocket_message {
    server 172.16.152.198:32763;
    server 172.16.152.199:32763;
    server 172.16.152.200:32763;
}

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

#支持ws://协议
server {
    listen 80;
    server_name websocket.xxxx.com;
    location / {
        proxy_pass http://websocket_message;
        proxy_http_version 1.1;
        proxy_read_timeout 300s;
        proxy_send_timeout 300s;
        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_set_header Upgrade $http_upgrade;
        proxy_set_header Connection $connection_upgrade;
    }
}

#支持wss://协议
server {
    listen 443 ssl;
    server_name websocket.xxxx.com;
    index index.html index.htm index.php;

    access_log /var/log/nginx/websocket.xxxx.com_access.log;
    error_log /var/log/nginx/websocket.xxxx.com_error.log;

    ssl_certificate   cert/xxx.pem;
    ssl_certificate_key  cert/xxx.key;
    ssl_session_timeout 5m;
    ssl_ciphers ECDHE-RSA-AES128-GCM-SHA256:ECDHE:ECDH:AES:HIGH:!NULL:!aNULL:!MD5:!ADH:!RC4;
    ssl_protocols TLSv1 TLSv1.1 TLSv1.2;
    ssl_prefer_server_ciphers on;
    keepalive_timeout 86400s;

    location / {
        proxy_pass http://websocket_message;
        proxy_http_version 1.1;
        proxy_read_timeout 300s;
        proxy_send_timeout 300s;
        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_set_header Upgrade $http_upgrade;
        proxy_set_header Connection $connection_upgrade;
    }
}

本地安装websocket工具

npm install -g wscat

$ npm install -g wscat
# 直接访问服务,不走nginx代理尝试是否正常,返回 Connected (press CTRL+C to quit) connection ok 表示正常
$ wscat -c ws://172.16.152.200:32763/webSocket/xxxxxxx
# 访问nginx反向代理地址尝试nginx代理是否配置正确(80/443)
$ wscat -c wss://websocket.xxxx.com/webSocket/xxxxxxx
$ wscat -c ws://websocket.xxxx.com/webSocket/xxxxxxx

在线websocket测试

EasySwoole-WebSocket在线测试工具EasySwoole在线WebSocket测试工具icon-default.png?t=M5H6http://www.easyswoole.com/wstool.htmlNginx配置Websocket反向代理_第1张图片

参考文章:nginx反向代理WebSocket | 飞污熊博客WebSocket协议相比较于HTTP协议成功握手后可以多次进行通讯,直到连接被关闭。但是WebSocket中的握手和HTTP中的握手兼容, 它使用HTTP中的Upgrade协议头将连接从HTTP升级到WebSocket。这使得WebSocket程序可以更容易的使用现已存在的基础设施。 WebSocket工作在HTTP的80和443端口并使用前缀ws://或者wss://进行协议标注,在建立连接时https://www.xncoding.com/2018/03/12/fullstack/nginx-websocket.html 

你可能感兴趣的:(Linux,大数据)