websocket nginx配置
生产环境,需要配置 wss
要点速览
shell
# Nginx 配置要点(必配)
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection "upgrade";
proxy_read_timeout 86400; # 长连接超时
# 注意事项
网页如果是 https 打开的,浏览器强制禁止连接 ws:// 明文,必须用 wss://
不需要单独买 WSS 证书,你网站的 HTTPS 域名 SSL 证书 直接复用即可,天然支持,也不需要额外配置nginx 完整版
nginx 配置 wss,前端直接连wss:const ws = new WebSocket("wss://你的域名.com/ws");
shell
server {
listen 443 ssl;
server_name 你的域名.com;
# HTTPS 证书配置
ssl_certificate /nginx/ssl/xxx.pem;
ssl_certificate_key /nginx/ssl/xxx.key;
# 【核心WSS配置】
location /ws {
proxy_pass http://127.0.0.1:8080; # 后端原生ws服务地址
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection "upgrade";
proxy_set_header Host $host;
# 长连接超时,防止断开
proxy_read_timeout 3600s;
proxy_send_timeout 3600s;
}
}