温馨提示×

Ubuntu Nginx如何实现WebSocket支持

小樊
40
2025-12-03 06:33:56
栏目: 智能运维

在Ubuntu上使用Nginx支持WebSocket,你需要进行以下几个步骤:

  1. 安装Nginx: 如果你还没有安装Nginx,可以使用以下命令来安装:

    sudo apt update
    sudo apt install nginx
    
  2. 安装WebSocket模块: 默认情况下,Nginx可能不包含WebSocket模块。你需要重新编译Nginx以包含这个模块。首先,安装编译Nginx所需的依赖项:

    sudo apt install build-essential libpcre3 libpcre3-dev zlib1g-dev openssl libssl-dev
    

    然后,下载Nginx的源代码并解压:

    wget http://nginx.org/download/nginx-1.21.6.tar.gz
    tar -zxvf nginx-1.21.6.tar.gz
    cd nginx-1.21.6
    

    配置Nginx以包含WebSocket模块:

    ./configure --with-http_ssl_module --with-http_v2_module --with-http_realip_module --with-http_addition_module --with-http_sub_module --with-http_dav_module --with-http_flv_module --with-http_mp4_module --with-http_gunzip_module --with-http_gzip_static_module --with-http_random_index_module --with-http_secure_link_module --with-http_stub_status_module --with-http_auth_request_module --with-threads --with-stream --with-http_slice_module --with-mail --with-mail_ssl_module --with-file-aio --with-http_v3_module
    

    编译并安装Nginx:

    make
    sudo make install
    

    注意:上面的配置命令包含了多个模块,你可以根据需要调整。

  3. 配置Nginx: 编辑Nginx配置文件(通常位于/usr/local/nginx/conf/nginx.conf),添加WebSocket支持:

    server {
        listen 80;
        server_name example.com;
    
        location / {
            proxy_pass http://localhost:3000;
            proxy_http_version 1.1;
            proxy_set_header Upgrade $http_upgrade;
            proxy_set_header Connection "upgrade";
            proxy_set_header Host $host;
        }
    }
    

    在这个配置中,proxy_pass指向你的WebSocket服务器地址和端口。proxy_set_header Upgrade $http_upgrade;proxy_set_header Connection "upgrade";这两行是关键,它们允许Nginx正确地处理WebSocket连接。

  4. 重启Nginx: 保存配置文件后,重启Nginx以应用更改:

    sudo /usr/local/nginx/sbin/nginx -s stop
    sudo /usr/local/nginx/sbin/nginx
    
  5. 测试WebSocket连接: 你可以使用WebSocket客户端(如websocat或浏览器中的JavaScript WebSocket API)来测试WebSocket连接是否正常工作。

通过以上步骤,你应该能够在Ubuntu上使用Nginx成功支持WebSocket。

0