nginx 既支持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;
    }
}

发表回复

您的电子邮箱地址不会被公开。 必填项已用 * 标注