title: Nginx Configuration: failed: Error during WebSocket handshake: Unexpected response code: 400
body: <p>I am struggling with nginx and websockets.</p>
  
  <p>My client is Javascript and I am using Fleck in the server code.</p>
  
  <p>So:  My JS:</p>
  
  <pre><code>var ws;
  var url = "wss://192.168.0.12:8080/";
  
  $(document).ready(function () {
  
  function Connect() {
      try {
          $("#lblConnectionStatus").html("Reconnecting...");
          if (ws instanceof WebSocket) {
              ws.close();
          }
          ws = new WebSocket(url);
          ws.binaryType = "arraybuffer";
          ws.onerror = function (e) {
              $("#divInternalMessangingStatus").html("Internal Messaging Error: " + e.message);
          };
          ws.onclose = function () {
              $("#divInternalMessangingStatus").html("Internal Messaging Closed:");
              Connect();
          };
          ws.onopen = function () {
              $("#divInternalMessangingStatus").html("Client connected");
  
          };
          ws.onmessage = function (e) {
              $("#divInternalMessangingStatus").html(e.data);
          };
      } catch (err) {
          $("#divInternalMessangingStatus").html(err);
      }
  }
  </code></pre>
  
  <p>NB I have for now hard coded the ip address my device is on.</p>
  
  <p>My C# code:</p>
  
  <pre><code>var server = new WebSocketServer("wss://0.0.0.0:8080/");
  
  server.Start(
      socket =&gt;
      {
              socket.OnOpen = () =&gt;
              {
              };
              socket.OnClose = () =&gt;
              {
              };
              socket.OnMessage = message =&gt;
              {
              }
      });
  </code></pre>
  
  <p>and my nginx config:</p>
  
  <pre><code>    server {
  listen 8080;
  server_name ws.serverlab.ca;
  
  listen               443;
  ssl                  on;
  ssl_certificate      /home/pi/web/localhost.crt;
  ssl_certificate_key  /home/pi/web/localhost.key;
  ssl_ciphers          HIGH:!aNULL:!MD5;
  #ssl_protocols TLSv1 TLSv1.1 TLSv1.2;
  
  
  
  location / {
    proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
    proxy_set_header Host $host;
    proxy_pass http://ws-backend;
    proxy_http_version 1.1;
    proxy_set_header Upgrade $http_upgrade;
    proxy_set_header Connection "upgrade";
  }
  }
  
  upstream ws-backend {
   # enable sticky session based on IP
  ip_hash;
  
  server 192.168.0.12:8080;
  #  server server02:3000;
  #  server server03:3000;
  </code></pre>
  
  <p>}</p>