nginx部署https后websocket需要将ws升级为wss报错:This request has been blocked; this endpoint must be available over WSS.
报错:
1.The page at 'XXX' was loaded over HTTPS, but attempted to connect to the insecure WebSocket endpoint 'ws://XXX/websocket/admin'. This request has been blocked; this endpoint must be available over WSS.
2.WebSocket connection to 'wss://XXX/websocket/admin' failed:
环境:linux服务器,nginx代理,websocket的ws改为wss
解决:
1.解决之前确认域名已配置证书,并且可正常通过域名访问网站。没配的以下配置中也有相关配置,cert文件夹
放到你的nginx安装位置文件夹下,一般是/usr/local/nginx/conf
2.nginx配置:
server {
#HTTPS的默认访问端口443。
listen 443 ssl;
#填写证书绑定的域名
server_name XXX.com;
#填写证书文件名称
ssl_certificate cert/XXX.com.pem;
#填写证书私钥文件名称
ssl_certificate_key cert/XXX.com.key;
ssl_session_cache shared:SSL:1m;
ssl_session_timeout 5m;
#自定义设置使用的TLS协议的类型以及加密套件(以下为配置示例,请您自行评估是否需要配置)
#TLS协议版本越高,HTTPS通信的安全性越高,但是相较于低版本TLS协议,高版本TLS协议对浏览器的兼容性较差。
ssl_ciphers ECDHE-RSA-AES128-GCM-SHA256:ECDHE:ECDH:AES:HIGH:!NULL:!aNULL:!MD5:!ADH:!RC4;
ssl_protocols TLSv1.1 TLSv1.2 TLSv1.3;
#表示优先使用服务端加密套件。默认开启
ssl_prefer_server_ciphers on;
location / {
root html/XXX;
index index.html index.htm;
try_files $uri $uri/ /index.html;
}
location /prod-api/{
proxy_set_header Host $http_host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header REMOTE-HOST $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_pass http://127.0.0.1:端口/;
}
!!!!!只有以下是websocket配置wss所需修改的内容,上面的只是配置https,如果已经配好https只需要看下面的就可以了!!!!!
//此处location /websocket和http://127.0.0.1:端口/websocket最后无需加斜杠/(nginx有个版本之后就不用加了,但是忘了哪个版本,可以查一下或者加上斜杠试一下,要加斜杠就都加,要不加就俩都不加),
//错误的写法:location /websocket/和http://127.0.0.1:端口/websocket/,这个'/websocket'需要填代码中的路径,随便填不生效
location /websocket {//这里也要改为自己的地址
proxy_pass http://127.0.0.1:端口/websocket; //将这里改为自己后台服务的端口,地址也要按照后台接口配置
//以下的不需要改
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header Host $host;
proxy_set_header X-NginX-Proxy true;
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection "Upgrade";
}
!!!!!到这!!!!!
# 图片配置 在本文没啥用
location /profile/ {
alias /XXX/XXX/;
autoindex on;
}
}
3.接口所指定的nginx配置路径,就上面的location /websocket
和http://127.0.0.1:端口/websocket
中的/websocket
这个路径:
根据你之前的websocket访问路径填写nginx配置路径
我这里之前是ws://XXX:端口/websocket/{userName}
改为wss后的地址是wss://XXX.com/websocket/{userName}
nginx中配置的就是location /websocket
和http://127.0.0.1:端口/websocket
如果之前路径不带参数,是:ws://XXX:端口/ws/websocket
那么改为wss后的地址是wss://XXX.com/ws/websocket
nginx中配置的就是location /ws/websocket
和http://127.0.0.1:端口/ws/websocket
访问的域名必须是可以访问https://XXX.com
的可用域名
@ServerEndpoint(value = "/websocket/{userName}")
@Component
public class WebSocketService {