nginx怎么配置websocker连接
要配置Nginx以支持WebSocket连接,需要进行以下步骤:
- 打开Nginx的配置文件(通常位于/etc/nginx/nginx.conf)。
- 在http部分添加以下配置:
map $http_upgrade $connection_upgrade {
default upgrade;
'' close;
}
server {
listen 80;
server_name example.com;
location / {
proxy_pass http://your_websocket_server;
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection "upgrade";
}
}
- 在map指令中,我们定义了一个变量
$connection_upgrade
,它的值依赖于请求头中的Upgrade字段。如果Upgrade字段存在且不为空,则将值设为"upgrade";否则,设为"close"。 - 在server块中,我们监听80端口并指定服务器名。location块用于处理所有请求,将其代理到你的WebSocket服务器。
proxy_http_version
指令将HTTP版本设置为1.1,proxy_set_header
指令设置了Upgrade和Connection请求头字段,以便支持WebSocket连接。
- 将
http://your_websocket_server
替换为实际的WebSocket服务器地址。 - 保存并关闭配置文件。
- 检查配置文件是否有语法错误:
nginx -t
。 - 重启Nginx服务:
systemctl restart nginx
(或者使用适合你的操作系统的命令)。
完成上述步骤后,Nginx将会正确代理WebSocket连接。确保你的WebSocket服务器正常运行,并且Nginx可以访问到它。