Home  >  Article  >  Operation and Maintenance  >  How Nginx implements WebSocket configuration

How Nginx implements WebSocket configuration

PHPz
PHPzOriginal
2023-11-08 10:37:561430browse

How Nginx implements WebSocket configuration

Nginx, as a high-performance web server and reverse proxy server, also has its own unique configuration method in processing WebSocket requests. WebSocket is a TCP-based protocol. The establishment of a WebSocket connection requires a three-way handshake. After the handshake is completed, two-way communication can occur between the client and the server. Below, we will introduce how to implement WebSocket configuration in Nginx, with specific code examples.

First, you need to add WebSocket related configuration to the Nginx configuration file.

http {
  ...
  upstream websocket {
    server localhost:9001;
  }
  ...
  map $http_upgrade $connection_upgrade {
      default upgrade;
      ''      close;
  }
  ...
  server {
      listen 80;
      server_name example.com;

      location / {
          proxy_pass http://websocket;
          proxy_http_version 1.1;
          proxy_set_header Upgrade $http_upgrade;
          proxy_set_header Connection $connection_upgrade;
          proxy_set_header Host $host;
      }
      ...
  }
  ...
}

In the above configuration, we added an upstream named "websocket" to specify the target server address and port of WebSocket. At the same time, the map directive is used to map $http_upgrade (client upgrade request header) and $connection_upgrade (nginx upgrade request header). In this way, by adding the "Upgrade" and "Connection" fields to the client's upgrade request header, Nginx can be triggered to upgrade the HTTP protocol to the WebSocket protocol, thereby achieving two-way communication.

In the server block, we use the proxy_pass directive to proxy all WebSocket requests to the websocket upstream, and set the protocol version and request header information. It should be noted that when proxying WebSocket in Nginx, the "Upgrade" and "Connection" request headers must be sent to the target server together, otherwise the connection will be closed, so these two request headers must be manually set through the proxy_set_header directive. Add to.

In addition, it should be noted that in the above configuration, we only listened to the HTTP (80) port. If you need to configure WebSocket under HTTPS, you need to add the following instructions in the server block:

listen 443 ssl;
ssl_certificate /path/to/cert.pem;
ssl_certificate_key /path/to/key.pem;

The above instructions are used to listen to the HTTPS (443) port and specify the path and name of the certificate and key files.

The following is a specific WebSocket server code example, implemented using Node.js:

const WebSocket = require('ws');

const server = new WebSocket.Server({ port: 9001 });

server.on('connection', (socket, req) => {
  console.log('Client connected');

  socket.on('message', (message) => {
    console.log(`Received message: ${message}`);
    socket.send(`Your message: ${message}`);
  });

  socket.on('close', () => {
    console.log('Client disconnected');
  });
});

In this code, we created a WebSocket server and listened to port 9001. After the connection is established, we output the "Client connected" information, and after receiving the client's message, return the message to the client, then listen for the closing event, and output the "Client disconnected" information.

Through the above code and configuration examples, we can implement the proxy and communication work of the WebSocket protocol in Nginx. It should be noted that there are still certain restrictions on the use of the WebSocket protocol. Specifically, the establishment process of the WebSocket connection is similar to the HTTP/HTTPS protocol. However, once the connection is successfully established, the communication between the two parties completely relies on the WebSocket protocol. It no longer relies on the HTTP/HTTPS protocol. Therefore, when using the WebSocket protocol, you need to avoid some conventional Web development restrictions, and at the same time, you must also pay attention to issues such as security and stability.

The above is the detailed content of How Nginx implements WebSocket configuration. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn