一、前端
http时候的写法:
ws://xx.xx.xx.xx:6532/ws?userId=xxxx
https的写法:
wss://www.xx.com/ws?userId=xxxx
二、nginx
修改之后完整的nginx配置如下:
# HTTP 服务配置
server {
listen 80;
server_name 你的域名;
return 301 https://$server_name$request_uri;
}
# HTTPS 服务配置
server {
listen 443 ssl;
server_name 你的域名;
ssl_certificate /path/to/cert.pem; 这里是你的证书路径
ssl_certificate_key /path/to/key.pem;这里是你的密钥路径
location /ws {
proxy_pass http://localhost:6532;
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;
proxy_set_header userId $arg_userId;
}
location / {
root /path/to/root;这里是你的项目存放地址
index index.html;
}
}
三、注意
这里的 location /ws 表示 WebSocket 服务的路径,而不是 URL。当请求的 URL 匹配到 /ws 路径时,将会被代理到 WebSocket 服务。
其中,proxy_set_header userId $arg_userId; 表示从请求 URL 的 query string 中获取 userId 参数的值,并将其作为自定义头信息 userId 发送到后端 WebSocket 服务。如果请求的 URL 中没有 userId 参数,则 $arg_userId 的值为空。