To set up Nginx to handle WebSocket connections for real-time applications, follow these steps:
Install Nginx: If Nginx is not already installed, you can install it using the package manager of your operating system. For example, on Ubuntu, you can run sudo apt-get install nginx
.
Configure Nginx: By default, Nginx configuration file is located at /etc/nginx/nginx.conf
. Open this file using a text editor.
Add WebSocket support: Inside the http
block of your Nginx configuration file, add the following lines to enable WebSocket support:
map $http_upgrade $connection_upgrade {
default upgrade;
'' close;
}
upstream websocket {
server <YOUR_WEBSOCKET_SERVER_IP>:<YOUR_WEBSOCKET_SERVER_PORT>;
}
server {
listen 80;
server_name <YOUR_DOMAIN_NAME>;
location / {
proxy_pass http://websocket;
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection $connection_upgrade;
}
}
Replace <YOUR_WEBSOCKET_SERVER_IP>
and <YOUR_WEBSOCKET_SERVER_PORT>
with the IP address and port of your WebSocket server. Replace <YOUR_DOMAIN_NAME>
with your domain name or IP address.
Save the configuration file and exit the text editor.
Test the configuration: Run sudo nginx -t
to check if the configuration file contains any errors. If the test is successful, you can proceed to the next step. Otherwise, review the error message and fix any issues.
Restart Nginx: Run sudo systemctl restart nginx
to apply the new configuration.
Now, Nginx will act as a reverse proxy for WebSocket connections, forwarding incoming WebSocket requests to your WebSocket server. This configuration allows Nginx to handle the initial HTTP handshake and upgrade the connection to the WebSocket protocol.