Websocket 下 nginx.conf配置

本文详细介绍如何在Nginx中正确配置WebSocket服务,避免301错误,确保WebSocket连接稳定运行。通过设置location路径、proxy_pass、proxy_http_version、proxy_set_header等参数,实现与后端服务器的有效通信。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Websocket 下 nginx.conf配置。 注意location路径最后不能有 “/”,会报301错误

location /biz/im/ws {
   proxy_pass http://192.168.3.142:9326;
   proxy_http_version 1.1;
   proxy_set_header Upgrade $http_upgrade;
   proxy_set_header Connection "Upgrade";
}
### Nginx 反向代理配置详解 要实现 Nginx 的反向代理功能,可以通过编辑 `nginx.conf` 文件来完成。以下是详细的配置说明: #### 基本结构 Nginx配置文件由多个模块组成,主要包括全局块、events 块、http 块以及 server 块等。对于反向代理而言,主要涉及的是 **http** 和 **server** 块。 --- #### 配置示例 以下是一个典型的 Nginx 反向代理配置示例[^1]: ```nginx user nginx; worker_processes auto; error_log /var/log/nginx/error.log notice; pid /var/run/nginx.pid; events { worker_connections 1024; } http { include /etc/nginx/mime.types; default_type application/octet-stream; sendfile on; keepalive_timeout 65; upstream backend { server xxx.xxx.xxx.xxx:8081; # 后端服务器地址和端口 } server { listen 80; # 监听的端口号 server_name localhost; # 主机名或域名 location /tomcat { # 定义路径前缀 proxy_pass http://backend/; # 将请求转发至后端服务器 } } } ``` 在此配置中: - 使用了 `upstream` 来定义一组后端服务器(可扩展为负载均衡场景)。如果仅有一个目标服务器,则可以直接在 `proxy_pass` 中指定其 URL。 - `location` 块中的 `/tomcat` 表明只有以该路径开头的请求会被代理到后端服务器。 --- #### WebSocket 支持 如果需要支持 WebSocket 协议,在 HTTP 块中需额外添加一些配置项[^3]: ```nginx http { ... map $http_upgrade $connection_upgrade { default upgrade; '' close; } server { listen 9016; server_name localhost; location /ws { proxy_pass http://xxx.xxx.xxx.xxx:9016/ws; proxy_http_version 1.1; proxy_set_header Upgrade $http_upgrade; proxy_set_header Connection $connection_upgrade; } } } ``` 此部分的关键在于启用 `Upgrade` 头部字段的支持,并确保协议升级机制正常运作。 --- #### 验证配置文件有效性 完成配置修改后,建议使用以下命令验证语法是否正确[^2]: ```bash /usr/local/nginx/sbin/nginx -t -c /usr/local/nginx/conf/nginx.conf ``` 或者简化版本: ```bash nginx -t ``` 若无误,重新加载配置即可生效: ```bash nginx -s reload ``` --- #### 生产环境优化 为了提高性能和稳定性,可以根据实际需求调整以下几个参数[^4]: - 设置工作线程数量为 CPU 核心数: ```nginx worker_processes auto; ``` - 调整单个工作进程的最大连接数: ```nginx events { worker_connections 1024; } ``` - 添加 MIME 类型支持并设置默认类型: ```nginx include mime.types; default_type application/json; ``` - 开启缓存加速静态资源访问: ```nginx sendfile on; tcp_nopush on; tcp_nodelay on; ``` ---
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值