http {
map $http_upgrade $connection_upgrade {
default upgrade;
'' close;
}
server {
......
location /ws {
proxy_pass http://172.16.20.95:8081;
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection $connection_upgrade;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
proxy_read_timeout 600s;
}
......
}
}
注释版配置,点击查看代码
http {
# 要使用 $connection_upgrade 变量,必须首先使用 map 指令来定义它,
map $http_upgrade $connection_upgrade {
default upgrade;
'' close;
}
server {
......
location /ws {
# 代理到 WebSocket 服务器
proxy_pass http://172.16.20.95:8081;
# WebSocket 需要 HTTP/1.1
proxy_http_version 1.1;
# 设置 Upgrade 头部
proxy_set_header Upgrade $http_upgrade;
# 设置 Connection 头部
proxy_set_header Connection $connection_upgrade;
# 通常建议设置 Host 头部
proxy_set_header Host $host;
# 发送真实 IP
proxy_set_header X-Real-IP $remote_addr;
# 发送 X-Forwarded-For
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
# 发送协议,如 http 或 https
proxy_set_header X-Forwarded-Proto $scheme;
# 不设置超时,或者设置一个较 高的超时时间
proxy_read_timeout 600s;
}
......
}
}
/ws
开头的路径,是 WebSocket 通信的常见前缀。
http块未配置map支持,nginx启动报错"unknown 'connection\_upgrade' variable"
解释
map $http_upgrade $connection_upgrade
:这条指令创建了一个新变量$connection_upgrade
,它基于$http_upgrade
变量的值。default upgrade
:如果$http_upgrade
包含任何值,$connection_upgrade
将被设置为"upgrade"
。'' close
:如果$http_upgrade
是空的,$connection_upgrade
将被设置为"close"
。
标签:upgrade,http,socket,header,nginx,connection,set,proxy,转发 From: https://www.cnblogs.com/2287keybord/p/18621531我希望、我希望你没有活在别人希望的希望里。