Nginx Config for SSL PHP site & Websockets WSS?



我正在尝试设置一个websocket连接(wss(。我的域名使用ssl(certbot(,由Nginx提供支持。我不确定如何配置我的/etc/nginx/sites-available/example.com文件。

server {
listen 443 ssl http2;
listen [::]:443 ssl http2;
...
}

我将以下内容添加到我的配置块中:

location /websocket {
proxy_pass         https://example.com;
proxy_http_version 1.1;
proxy_set_header   Upgrade $http_upgrade;
proxy_set_header   Connection "upgrade";
proxy_set_header   Host $host;
}

连接方式时:wss://example.com/,我收到错误

WebSocket connection to 'wss://example.com/' failed: 
Error during WebSocket handshake: Unexpected response code: 200

大多数例子都使用 nodejs 框架来为他们的网站提供服务,但我使用的是 php。是否有任何教程可以指导我,或者有人知道如何配置我的配置文件?谢谢!

我发现proxy_pass https://example.com;在您的nginx配置中,howereverhttps://example.com是http服务器而不是websocket服务器,因此您得到了响应代码200

这是一个例子

location ~ ^/websocket/(.*$) {
tcp_nodelay on;
keepalive_timeout  1200s 1200s;
keepalive_requests 100000;
proxy_pass http://127.0.0.1:51966/$1;
proxy_read_timeout 1200s;
proxy_send_timeout 1200s;
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;
}

51966 是 WebSocket 正在侦听的端口

最新更新