Nginx配置websocket 和 socket

首先明确 websocket 和 socket 有啥区别才行, 要了解他们之间的区别就要了解什么是 网络7层协议

  • websocket/socket 区别参考: https://blog.csdn.net/mcj19970614/article/details/80453285

  • 七层协议参考: https://www.cnblogs.com/carlos-mm/p/6297197.html


配置websocket简单,和配置一般的 location 差不多,举例如下:

upstream love-push {
    ip_hash;
    server 192.168.2.173:9094;
}

server {
    listen 9094;
    server_name xxx.yyy.cn;

    error_log /data/nginx/logs/push.error.log ;
    access_log /data/nginx/logs/push.access.log ksformat ;

    location /socket.io/ {
        proxy_pass http://love-push;
        proxy_next_upstream http_502 http_504 error timeout invalid_header;

        proxy_http_version 1.1;
        # proxy_set_header Connection "";

        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection "upgrade";
        # proxy_set_header Host $host;
        proxy_set_header Host "xxx.yyy.cn";
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
    }
}

配置 socket 需要nginx 在编译的时候 使用了 --with-stream

./configure --with-stream

另外 stream的配置(注意:不是upstream哦)需要在http之外,否则会报错;
这里大家可以思考下
为什么必须放到 http之外或者说是和 http 同级别呢?
欢迎留言

配置举例

stream { 
          
    upstream test_socket {
    
        hash $remote_addr consistent;
        server 192.168.2.3:1245 weight=5 max_fails=3 fail_timeout=30s;
  
    }
    
    server {
        listen 3389; 
        proxy_connect_timeout 1s; 
        proxy_timeout 3s;
        proxy_pass test_socket;
    }

}

你可能感兴趣的:(Nginx配置websocket 和 socket)