Nginx 配置文件通常位于 /etc/nginx/nginx.conf
,也可以在 /etc/nginx/conf.d/
下创建新的配置文件,例如 websocket.conf。
/etc/nginx/nginx.conf
nginxhttp { upstream websocket { server localhost:9301; # 定义上游 WebSocket 服务器 } server { listen 9300; # 监听 9300 端口 location / { proxy_pass http://websocket; # 将请求代理到上游服务器 proxy_http_version 1.1; # 使用 HTTP/1.1 proxy_set_header Upgrade $http_upgrade; # 设置 Upgrade 头 proxy_set_header Connection "upgrade"; # 设置 Connection 头 proxy_set_header Host $host; # 设置 Host 头 proxy_set_header X-Real-IP $remote_addr; # 设置真实 IP proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; # 设置转发的 IP proxy_set_header X-Forwarded-Proto $scheme; # 设置转发的协议 } } }
/etc/nginx/conf.d/websocket.conf
nginxupstream websocket { server localhost:9301; # 定义上游 WebSocket 服务器 } server { listen 9300; # 监听 9300 端口 location / { proxy_pass http://websocket; # 将请求代理到上游服务器 proxy_http_version 1.1; # 使用 HTTP/1.1 proxy_set_header Upgrade $http_upgrade; # 设置 Upgrade 头 proxy_set_header Connection "upgrade"; # 设置 Connection 头 proxy_set_header Host $host; # 设置 Host 头 proxy_set_header X-Real-IP $remote_addr; # 设置真实 IP proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; # 设置转发的 IP proxy_set_header X-Forwarded-Proto $scheme; # 设置转发的协议 } }
upstream websocket
: 定义名为 websocket 的上游服务器,指定 WebSocket 服务器的地址(localhost:9301)。server
: 创建一个 Nginx 服务器块,监听来自客户端的 WebSocket 连接请求。location /
: 匹配所有请求,将其代理到上游服务器。proxy_pass
: 将请求转发到定义的上游服务器。proxy_http_version
: 指定使用 HTTP/1.1,以支持 WebSocket。proxy_set_header
: 设置请求头,以支持 WebSocket 协议。本文作者:澳门🇲🇴上班的IT人
本文链接:
版权声明:本博客所有文章除特别声明外,均采用 BY-NC-SA 许可协议。转载请注明出处!