代理WebSocket的示例配置
# /etc/nginx/conf.d/proxy-http.conf
server {
listen 8080;
server_name api.mydomain.com;
location / {
proxy_pass http://backend;
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection "upgrade";
proxy_connect_timeout 5;
proxy_read_timeout 90s;
proxy_send_timeout 10s;
}
}
参数说明
- proxy_http_version
设置代理到upstream的http协议版本,必须设置;默认可能会采用http/1.0,会导致协议升级切换失败。
- Proxy header Upgrade & Connection
使nginx将协议切换到WebSocket,必须明确定义、或判断客户端是否需要升级协议并向upstream传递该值。文章来源:https://www.toymoban.com/news/detail-573953.html
http {
# 匹配变量http_upgrade的值,根据匹配情况为变量connection_upgrade赋值
map $http_upgrade $connection_upgrade {
default upgrade;
'' close;
}
server {
...
location /chat/ {
proxy_pass http://backend;
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection $connection_upgrade;
}
}
- proxy_read_timeout
定义从代理服务器读取响应的超时时间;保持长连接最终依靠的是心跳机制,此值根据客户端心跳间隔合理设置,一般比心跳间隔大一些时间。文章来源地址https://www.toymoban.com/news/detail-573953.html
到了这里,关于nginx代理WebSocket配置的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!