Rabikant
Posted on March 9th
Setup secure WebSocket with nginx
"In this blog we will learn how to secure websocket with nginx."
WebSockets have become the basis for a new era of web applications, considering that full-duplex communication between the client and server has become possible with real-time efficiency. WebSockets have become significant for various today’s web applications, starting with live chat software and ending with online gaming applications or financial market indicators. However, as with any common protocol, security always poses a big issue that needs to be addressed. In this blog post, we will explain how to configure WebSocket connection with Nginx in reverse proxy mode and using SSL/TLS for encrypted connection.
What is nginx?
Nginx, pronounced as ‘engine-x’ is a high-performance web server, reverse proxy server and load balancer. First appeared in June 2004 by Igor Sysoev, Nginx quickly became popular as one of the most used web servers worldwide; it is especially beneficial to handle numerous connections with low RAM usage. This makes it fit for current web applications that require the efficient handling of large traffic.
Key Features of Nginx
- Web Server: Fundamentally, Nginx is a web server which, unlike Apache, is used to deliver static content including: HTML, images and CSS files. It is optimized for high traffic hence it is commonly used by large websites and application development.
- Reverse Proxy: In perusing the use of Nginx one of its most common application is for reverse proxy. In this role it helps mediate between client requests and backend servers such as application servers or databases. In this way we can find balance in terms of serving requests to multiple servers and also use nginx to lighten the load and cache content.
- Load Balancer: Based on the results achieved, Nginx is very efficient as a load balancer because it works to distribute incoming network traffic across many servers. This enables efficient use of resources, high system utilization and reduced response time to clients. Therefore, its load distribution can be round-robin, IP-hash or least connection based with regard to the requirements of infrastructures.
- SSL Termination: Nginx can be used quite often for SSL/TLS termination. This means that it can handle duties of the HTTPS traffic interception and decryption before forwarding it to back end servers. Relocation of this work from the application servers offsets their CPU load while simplifying management of the SSL certificates.
- WebSocket Support: Contemporary Web applications are very much dependent on means of real-time communication such as WebSockets. Nginx is designed to manage WebSocket connections, and thus useful in applications such as chat applications, multiplayer games, and live data streaming.
- Content Caching: It generates cache from static and dynamic content, which decreases the frequency of back-end sever engagement with similar requests. This enhances the performance of delivering content to the users.
- HTTP/2 and gRPC Support: Nginx also supports HTTP/2, which increases website speed since multiple request and response can occur simultaneously within a single connection. It also supports gRPC which is a newer generation of high developers communication protocol for many microservice systems.
Why Use Nginx?
Nginx is known for its scalability feature; it consumes resources and can comfortably attend to tens and thousands of connections. It is event driven hence uses model of operation other than process or threading as used by conventional webservers such as Apache.0.4
Moreover, Nginx enjoys easy configuration and is also very flexible. For that it offers a plethora of modules that enables it to be fine-tuned depending on the kind of project, from a basic static content site to a complex multi tier application or a multitude of microservices architecture.
What are WebSockets?
Before I proceed further with the setup, allow me to spend few words of introduction about WebSockets to the readers. WebSockets are long-standing connections between the server and the client while HTTP is an RR protocol. WebSockets are a persistent connection where the server may push data down to the client without the instance of the client pulling the information up.
In the context of modern web applications, WebSockets are used for real-time functionalities such as:
The use of social media like live chat and messaging. Web applications used in collaboration – especially in real time such as Google docs.
Live stream of data and trading platforms of the financial markets
- Multiplayer games and more
However, availability and usage and variations and operations of WebSockets must be safeguarded by several factors such as the information. That is where the next server comes to rescue it as reverse proxy to ensure the safety of the Websocket connections.
Why Use Nginx as a Reverse Proxy?
To the surprise of many it is an open source web server and reverse proxy with high performance and security that people know today as Nginx. In WebSocket communications, it is possible for Nginx to proxy WebSocket server, manage SSL termination, load balancing and to add layers of security.
By using Nginx, you can also:
- Shutdown SSL/TLS links Increases the protection to WebSocket servers Load balancing is the process through which scale applications can be managed efficiently. Websocket Traffic Logging and Monitoring
Prerequisites
Before setting up secure WebSocket connections, ensure that the following prerequisites are met:
Nginx installed: Make sure you have Nginx installed on your server. If not, install it by running:
sudo apt update sudo apt install nginx- SSL Certificate: If you want to ensure your message is secure you will have to use an SSL certificate. This could be one created by the owner of the website or one created by an authentic CA such as Let’s Encrypt.
- WebSocket Server: Check if WebSocket server is successfully created with a specific port. For example, an application's server could be referred to as running on port 3000.
Generate an SSL Certificate
The next requirement is that you should have SSL certificate installed on the system In case you do not possess one, then you can generate a self-signed SSL certificate or generate the same through your chosen Certificate Authority. Here’s how you can generate a self-signed SSL certificate:
sudo openssl req -x509 -nodes -days 365 -newkey rsa:2048 -keyout /etc/nginx/ssl/nginx.key -out /etc/nginx/ssl/nginx.crt
To borrow the words of heart, the first one /etc/nginx/ssl/nginx.crt is the certificate and second one /etc/nginx/ssl/nginx.key is the private key. The certificate is this: /etc/nginx/ssl/nginx.crt.
Next, it takes your information like your domain name, your company name, and where you are located. After following this step, you will be ready to have the self-signed certificate up and running.
Setting up WebSocket on Nginx
Fortunately, Nginx supports WebSockets, though they should be configured in the right way to proxy WebSocket connections successfully. Following is a sample Nginx configuration to listen WebSocket connections.
Example Configuration
Edit your Nginx configuration file (usually located at /etc/nginx/nginx.conf or /etc/nginx/sites-available/default), and set up the following reverse proxy configuration:
server {
listen 443 ssl;
server_name yourdomain.com;
ssl_certificate /etc/nginx/ssl/nginx.crt;
ssl_certificate_key /etc/nginx/ssl/nginx.key;
location / {
proxy_pass <http://localhost:3000>;
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection "Upgrade";
proxy_set_header Host $host;
# Optional WebSocket timeouts
proxy_read_timeout 60s;
proxy_send_timeout 60s;
}
}
This configuration achieves the following:
- Listening on port 443: Nginx intakes secure HTTPS connections on the port number 443.
- SSL Certificate: Generated SSL certificate and key are to be used by Nginx.
- Proxy WebSocket traffic: proxy_pass http://localhost:3000 sends all the WebSocket connections to the WebSocket server on the port 3000.
- Handle WebSocket upgrade headers: Using the HTTP ‘Upgrade’ header, WebSockets change the communication from the HTTP to the WebSocket protocol. Notice that proxy_set_header Upgrade $http_upgrade; and proxy_set_header Connection "Upgrade"; are really important to support WebSocket.
- Timeouts: WebSocket connections can last for a long time. Controlling of idle connections is facilitated by the setting of proxy_read_timeout’ and proxy_send_timeout’.
Redirect from Http to Https
To make all the connections secure you should also configure the redirection from HTTP (port 80) to HTTPS (port 443). Add another server block to your configuration:
server {
listen 80;
server_name yourdomain.com;
location / {
return 301 https://$host$request_uri;
}
}
This configuration forces all HTTP requests to be redirected to HTTPS, ensuring that the WebSocket connection is secure.
Restart Nginx
After making the changes to your Nginx configuration file, you’ll need to restart Nginx for the changes to take effect. Run the following command:
sudo systemctl restart nginx
Test the WebSocket Connection
To test whether everything is working correctly, you can use a WebSocket client to initiate a connection. Here’s an example using JavaScript in the browser’s developer console:
const socket = new WebSocket('wss://yourdomain.com');
socket.onopen = function() {
console.log('WebSocket connection established');
};
socket.onmessage = function(event) {
console.log('Message from server:', event.data);
};
socket.onerror = function(error) {
console.log('WebSocket error:', error);
};
socket.onclose = function() {
console.log('WebSocket connection closed');
};
This client code connects to the WebSocket server using the secure wss:// protocol. If you are connected successfully, you should view a message along the lines of WebSocket connection established.
Monitor WebSocket Connections
Of course, logs in Nginx can be useful to analyse your WebSocket traffic. You can check the logs using the following commands:
sudo tail -f /var/log/nginx/access.log
sudo tail -f /var/log/nginx/error.log
These logs can help you troubleshoot any issues with the WebSocket connection.
Conclusion
The first step towards implementing real-time applications which are secure is to create a secure WebSocket connection via Nginx. Nginx not only assists with this but it also assists with SSL termination and load balancing, traffic monitor and hence the preferred platform for handling WebSocket connections.
With the help of the information given in this tutorial you will be able to securely setup fast WebSocket connection utilizing Nginx in reverse proxy setup. You can now easily secure WebSocket communications over HTTPS, and whether you’re developing a chat app, a game or any other real-time application, do so with confidence.
