ws是websocket的统一资源标识符,wss对于ws相当于https对于http,今天把ws部署到服务器的时候提示错误了:
Mixed Content: The page at 'https://domain.com/' was loaded over HTTPS, but attempted to connect to the insecure WebSocket endpoint 'ws://x.x.x.x:xxxx/'. This request has been blocked; this endpoint must be available over WSS.
服务器使用的是nginx转发80到443上,在443端口绑定的ssl证书。
那么这里使用websocket的服务也肯定要由ws改成wss。所以在前端修改一下:
if ("WebSocket" in window) {
let wsClient = new WebSocket("wss://www.域名.com");
后端也需要做相应的修改,修改nginx/conf中的nginx.conf文件:
# HTTPS server
#
server {
listen 443 ssl;
server_name www.域名.com/;
ssl_certificate 1_www.域名.com_bundle.crt;
ssl_certificate_key 2_www.域名.com.key;
#这是新添加的
location /wss/ {
proxy_pass http://127.0.0.1:3000/; #通过配置端口指向部署websocket的项目
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection "Upgrade";
proxy_set_header X-real-ip $remote_addr;
proxy_set_header X-Forwarded-For $remote_addr;
}
#这上面是新添加的
location / {
proxy_pass http://127.0.0.1:3000;
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection "upgrade";
}
}
在centos中输入pm2 restart all,重启node网站。ok。
输入redis-cli,进入redis,输入keys * 打印所有的key也显示正常。
使用了nginx代理转发wss之后,获取的IP是127.0.0.1。
获取IP的方法是:
wss.on('connection', function connection(ws, req) {
// console.log(req);
const ip = req.connection.remoteAddress;
打印的req为:
这里继续修改nginx的conf为:
location /wss/ {
proxy_pass http://127.0.0.1:3000/; #通过配置端口指向部署ws的项目
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection "Upgrade";
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header Host $host;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
}
修改后重新打印输出为:
这里便有了新添加的几项,里面有我们真实的IP地址,便可以获取到IP了。
How to get the IP address of the client?
When the server runs behind a proxy like NGINX, the de-facto standard is to use the X-Forwarded-For
header.
wss.on('connection', function connection(ws, req) {
const ip = req.headers['x-forwarded-for'].split(/\s*,\s*/)[0];
});