Nginx配置支持WebSocket功能

发布于:2024-07-11 ⋅ 阅读:(54) ⋅ 点赞:(0)

刚部署一个项目需要使用到WebScoket实现。但通过域名指向NG做了反向代理,发现通过域名访问不了,通过查找资料后发现需要在Nginx添加WebSocket的转发配置。

一、网上通用配置

在网上找到大部分配置如下所示

location /websocket/ {
        proxy_pass http://myserver;
 
        proxy_http_version 1.1;
        proxy_read_timeout 360s;   
        proxy_redirect off;   
        proxy_set_header Upgrade $http_upgrade; 
        proxy_set_header Connection "upgrade";    #配置连接为升级连接
        proxy_set_header Host $host:$server_port;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header REMOTE-HOST $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
}

使用如上连接,如果所有的连接仅仅为 "ws" 协议的请求是没有问题的,但是如果要及支持 http 请求又支持 ws 请求上述配置就不起作用了。

二、既支持http又支持 ws 的配置。

 通过nginx官方关于WebSocket的配置得知,可以自定义变量。故配置如下,就可以做到既支持 ws 请求,又支持 http请求。

http {
 
   #自定义变量 $connection_upgrade
    map $http_upgrade $connection_upgrade { 
        default          keep-alive;  #默认为keep-alive 可以支持 一般http请求
        'websocket'      upgrade;     #如果为websocket 则为 upgrade 可升级的。
    }
 
    server {
        ...
 
        location /chat/ {
            proxy_pass http://backend;
            proxy_http_version 1.1;
            proxy_set_header Upgrade $http_upgrade; #此处配置 上面定义的变量
            proxy_set_header Connection $connection_upgrade;
        }
    }
}

在这个配置中:

map $http_upgrade $connection_upgrade 块用于根据客户端发送的 Upgrade 头的值设置 Connection 头的值。

proxy_pass 指向WebSocket服务的后端地址。

proxy_http_version 1.1 指定使用HTTP/1.1版本以保持连接打开。

proxy_set_header Upgrade $http_upgrade 和 proxy_set_header Connection $connection_upgrade 确保正确的头被发送到后端,以便它可以识别WebSocket连接。

确保您的Nginx版本是1.3或更高,以支持WebSocket。