The modern application uses Websockets to update application data in real time like live updates or chat. If the application is deployed with Apache, it needs to be set up correctly to manage WebSocket (wss://) requests. In this simple guide, we will show you how to configure Apache to handle these requests. You’ll learn how to enable the right modules and adjust your VirtualHost settings. By the end, your Apache server will be ready to handle WebSocket connections, keeping your application running smoothly.
For example, I have an Next.JS application running on url https://example.com but the websocket requests looks like wss://example.com/_next/webpack-hmr. To handle a WebSocket request (wss://) using Apache’s ProxyPass, you need to make sure that the Apache server is properly configured to proxy WebSocket connections.
Here’s a simple configuration example:
Enable the necessary Apache modules
You need to ensure that the proxy, proxy_http, proxy_wstunnel, and rewrite modules are enabled. You can enable these modules using the following commands:
sudo a2enmod proxy
sudo a2enmod proxy_http
sudo a2enmod proxy_wstunnel
sudo a2enmod rewrite
Configure the VirtualHost
Add the following configuration to your Apache VirtualHost file (typically found in /etc/apache2/sites-available/):
<VirtualHost *:80>
ServerName example.com
# Other configurations (like DocumentRoot, etc.)
# Proxy WebSocket connections
RewriteEngine On
RewriteCond %{HTTP:Upgrade} =websocket [NC]
RewriteRule /(.*) wss://localhost:3000/$1 [P,L]
# Proxy other HTTP requests
ProxyPass / http://localhost:3000/
ProxyPassReverse / http://localhost:3000/
</VirtualHost>
In this configuration:
- RewriteRule: Handles WebSocket (ws://) connections by forwarding them to the backend server (e.g., running on port 3000).
- ProxyPass/ProxyPassReverse: Handles regular HTTP traffic.
Restart Apache
After making the changes, restart Apache to apply the configuration:
sudo systemctl restart apache2
This configuration should properly proxy WebSocket connections (wss://) for example.com/_next/webpack-hmr through Apache.
Conclusion
By following the steps outlined in this article, you can successfully configure Apache to handle WebSocket (wss://) requests, ensuring seamless communication between your client and backend servers. Properly enabling the necessary modules and setting up the correct ProxyPass and RewriteRule configurations will allow Apache to efficiently proxy WebSocket connections, as well as manage regular HTTP traffic