nginx配置http协议转发wss
时间: 2024-11-29 19:15:16 浏览: 22
Nginx可以作为反向代理服务器,将HTTP请求转换为HTTPS(Secure Sockets Layer,即WebSockets Secure,WSS),以便安全地支持WebSocket通信。以下是基本的Nginx配置示例,用于将HTTP流量重定向到HTTPS并处理WSS连接:
```nginx
server {
listen 80; #监听HTTP端口80
server_name yourdomain.com;
# 使用HTTPS转义
rewrite ^ https://$host$request_uri? permanent;
}
server {
listen 443 ssl; #监听HTTPS端口443
server_name yourdomain.com;
ssl_certificate /path/to/your/certificate.pem;
ssl_certificate_key /path/to/your/private/key.pem;
location /ws/ { # 指定WebSocket路径
proxy_pass http://localhost:8080/ws; # 转发到本地WebSocket服务
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header 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;
}
}
```
在这个配置里,首先将所有HTTP请求重定向到HTTPS,然后在`location`块中设置了一个针对`/ws/`路径的规则,通过`proxy_pass`指令将WebSocket请求从HTTPS代理到运行在`localhost:8080`的WS服务。
阅读全文