一台服务器上的nginx +节点+ ssl + websockets

时间:2018-07-04 10:40:33

标签: node.js ssl nginx websocket socket.io

我已经能够找到与nginx,node,ssl和websocket的各种组合有关的指南,但是从来没有在一起,也从来没有在单个服务器上。

最终,这就是我所追求的,而且我不确定是否有可能:

  • 单个服务器(Ubuntu 14.04)
  • 强制HTTPS(浏览到http://site会转发到https://)
  • 节点应用程序托管在localhost:3000
  • 节点应用程序使用Web套接字
  • 这是一个单页面的React应用程序,根本没有路由,所以我不需要路由。我再说一遍,我只托管一个页面,没有任何导航。

通过以下配置,我可以正常使用websockets之外的所有东西-如果客户端直接浏览到节点服务器并且不使用nginx(浏览http://my.domain:3000),客户端会抛出该错误:< / p>

bundle.js:26 WebSocket connection to 'wss://<my domain>/socket.io/?EIO=3&transport=websocket&sid=x1uQtRzF3gYYEvfIAAAi' failed: Error during WebSocket handshake: Unexpected response code: 400

server {
  listen 80;
  return 301 https://my/domain$request_uri;
}

server {
  listen 443 ssl;
  listen [::]:443;

  ssl_certificate     /path/cert.crt;
  ssl_certificate_key /path/key.key;
  ssl_session_cache shared:SSL:10m;

  server_name blaze.chat;

  location / {
    proxy_set_header        X-Real-IP $remote_addr;
    proxy_set_header        X-Forwarded-For $proxy_add_x_forwarded_for;
    proxy_set_header        X-Forwarded-Proto $scheme;
    proxy_pass              http://localhost:3000;
    proxy_http_version      1.1;
    proxy_set_header        Upgrade $http_upgrade;
    proxy_set_header        Host $host;
    proxy_redirect          http://localhost:3000 https://my.domain;
  }

}

1 个答案:

答案 0 :(得分:0)

正确,可以正常工作...找到了很多类似的文章,但缺少以下关键内容:

proxy_set_header Connection "upgrade";
proxy_read_timeout 86400;

就我而言,没有这些行,websockets将无法工作,这与许多其他问类似问题的帖子相反。不知道有什么区别。具有讽刺意味的是,它在Nginx Websocket代理文档中被列为一项要求。。。我应该从那里开始。

http://nginx.org/en/docs/http/websocket.html

请注意,我只是在/的根路径上使用它,效果很好。