Nginx配置websocket

1.修改http区域的配置:

路径:/etc/nginx/nginx.conf(每个人的路径可能不一样)

编辑nginx.conf,在http区域内一定要添加下面配置:

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

map指令的作用:
该作用主要是根据客户端请求中$http_upgrade的值,来构造改变$connection_upgrade的值,即根据变量$http_upgrade的值创建新的变量$connection_upgrade,创建的规则就是{}里面的东西。其中的规则没有做匹配,因此使用默认的,即$connection_upgrade的值会一直是upgrade。然后如果$http_upgrade为空字符串的话,那值会是close。

2.修改server区域的配置:

路径:/etc/nginx/conf.d/netcore.conf(每个人的路径可能不一样,文件名也是自定义的)

该路径是根据nginx.conf里面的配置来的:

编辑路径下的文件netcore.conf

#之前配的内容:
server {
    listen 80;
    location / {
        proxy_pass http://localhost:5000;
        proxy_http_version 1.1;
        proxy_cache_bypass $http_upgrade;
        proxy_set_header Host $host;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection keep-alive;
        
    }
}
#修改为:
server {
    listen 80;
    location / {
        proxy_pass http://localhost:5000;
        proxy_http_version 1.1;
        proxy_cache_bypass $http_upgrade;
        proxy_set_header Host $host;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection "Upgrade";
        proxy_read_timeout 3600s;               
    }
}

其中proxy_read_timeout默认是60s,60s内不操作websocket就会断开,我们可以把它设置大一点,这里为设置为一个小时。

配置完成后重启下nginx:

nginx -s reload

3.连接测试

以下是websocket的连接测试

websocket连接成功了,但是我发现该站点的post请求方式失败了,返回状态码400。原因是nginx配置导致的。

查看nginx日志

解决方法:我们把websocket和http的location分开来配置,配置如下

server {
    listen 80;
     location / {
        proxy_pass http://localhost:5000;
        proxy_http_version 1.1;
        proxy_cache_bypass $http_upgrade;
        proxy_set_header Host $host;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection keep-alive;
        
    }
    #websocket path
    location /api/MessageRelease {
        proxy_pass http://localhost:5000/api/MessageRelease;
        proxy_http_version 1.1;
        proxy_cache_bypass $http_upgrade;
        proxy_set_header Host $host;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection "Upgrade";
        proxy_read_timeout 3600s;              
    }
}

配置完成后重启下nginx:

nginx -s reload

这样websocket和http的请求就不会冲突了。

参考文章:

https://www.cnblogs.com/kevingrace/p/9512287.html

https://blog.csdn.net/cm786526/article/details/79939687

https://www.cnblogs.com/piperck/p/7066286.html

原文地址:https://www.cnblogs.com/zt102545/p/13940235.html