如果你的项目是https域名访问的,那么你去请求websocket的时候,如果不是wss协议的websocket接口,会报错。所以本文将讲述如何在Nginx中为websocket配置证书。
- 首先假设你的websocket接口是写在一个java项目中,这个项目之前已经配置了https证书,如果项目还没有配置https证书,可以参考前后端分离项目域名配置Https。所以现在的项目nginx配置应该是如下:
upstream api.demoProject.com{
server 192.168.1.110:8090 weight=1;
}
server {
listen 443 ssl;
ssl on;
ssl_certificate /etc/letsencrypt/live/api.demoProject.com/fullchain.pem; #注意域名填写正确
ssl_certificate_key /etc/letsencrypt/live/api.demoProject.com/privkey.pem; #注意域名填写正确
ssl_session_timeout 5m;
ssl_protocols TLSv1 TLSv1.1 TLSv1.2;
ssl_ciphers ECDH:AESGCM:HIGH:!RC4:!DH:!MD5:!aNULL:!eNULL;
ssl_prefer_server_ciphers on;
listen 80;
server_name api.demoProject.com;
location / {
client_max_body_size 100M;
proxy_set_header Host $host;
proxy_pass api.demoProject.com;
}
#error_page 404 /404.html;
# redirect server error pages to the static page /50x.html
#
error_page 500 502 503 504 /50x.html;
location = /50x.html {
root /usr/share/nginx/html;
}
}
- 只需要在location中增加以下两行即可支持wss
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection "upgrade";
增加后的配置如下:
upstream api.demoProject.com{
server 192.168.1.110:8090 weight=1;
}
server {
listen 443 ssl;
ssl on;
ssl_certificate /etc/letsencrypt/live/api.demoProject.com/fullchain.pem; #注意域名填写正确
ssl_certificate_key /etc/letsencrypt/live/api.demoProject.com/privkey.pem; #注意域名填写正确
ssl_session_timeout 5m;
ssl_protocols TLSv1 TLSv1.1 TLSv1.2;
ssl_ciphers ECDH:AESGCM:HIGH:!RC4:!DH:!MD5:!aNULL:!eNULL;
ssl_prefer_server_ciphers on;
listen 80;
server_name api.demoProject.com;
location / {
client_max_body_size 100M;
proxy_set_header Host $host;
proxy_set_header Upgrade $http_upgrade; #支持wss
proxy_set_header Connection "upgrade"; #支持wss
proxy_pass api.demoProject.com;
}
#error_page 404 /404.html;
# redirect server error pages to the static page /50x.html
#
error_page 500 502 503 504 /50x.html;
location = /50x.html {
root /usr/share/nginx/html;
}
}