编辑
2024-12-04
Nginx
0
请注意,本文编写于 196 天前,最后修改于 196 天前,其中某些信息可能已经过时。

目录

配置文件位置
配置文件内容
配置文件説明

配置文件位置

Nginx 配置文件通常位于 /etc/nginx/nginx.conf,也可以在 /etc/nginx/conf.d/ 下创建新的配置文件,例如 websocket.conf。

配置文件内容

/etc/nginx/nginx.conf

nginx
http { 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

nginx
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; # 设置转发的协议 } }

配置文件説明

  • upstream websocket: 定义名为 websocket 的上游服务器,指定 WebSocket 服务器的地址(localhost:9301)。
  • server: 创建一个 Nginx 服务器块,监听来自客户端的 WebSocket 连接请求。
  • location /: 匹配所有请求,将其代理到上游服务器。
  • proxy_pass: 将请求转发到定义的上游服务器。
  • proxy_http_version: 指定使用 HTTP/1.1,以支持 WebSocket。
  • proxy_set_header: 设置请求头,以支持 WebSocket 协议。
如果对你有用的话,可以打赏哦
打赏
ali pay
wechat pay

本文作者:澳门🇲🇴上班的IT人

本文链接:

版权声明:本博客所有文章除特别声明外,均采用 BY-NC-SA 许可协议。转载请注明出处!