Nginx Config for SSL PHP网站和Websockets WSS?

时间:2018-09-28 22:44:41

标签: php nginx websocket

我正在尝试设置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。有没有可以指导我的教程,或者有人对如何配置我的配置文件有想法吗?谢谢!

1 个答案:

答案 0 :(得分:0)

我在您的nginx配置中找到了proxy_pass https://example.com;,但是https://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监听的端口