How to handle WebSocket connections with mod_proxy_wstunnel?
Jul 05, 2025 am 12:47 AMThe mod_proxy_wstunnel module is the key to Apache's handling of WebSocket connections, which ensures that requests are correctly forwarded to the backend and the connection is constantly opened. 1. First enable the mod_proxy and mod_proxy_wstunnel modules, and restart the Apache service; 2. Use the ws:// or wss:// protocol when configuring VirtualHost to ensure path matching; 3. Add the RequestHeader to set Upgrade and Connection headers to support protocol switching; 4. Configure a valid certificate and point to the wss:// address when using SSL/TLS; 5. Test the connection through the browser console, wscat and other tools, and check the Apache log troubleshooting problem. As long as the protocol upgrade and path mapping are configured correctly, WebSocket can run stably.
When handling WebSocket connections, if you use Apache as the reverse proxy server, the mod_proxy_wstunnel module is the key component you need. It allows you to correctly forward WebSocket requests to the backend application server without interrupting the connection or downgrading to long polling.
Below are some key points and configuration suggestions that need to be paid attention to in actual operation.
Enable the necessary modules
Before starting configuration, make sure your Apache has the following modules enabled:
-
mod_proxy
-
mod_proxy_wstunnel
You can enable these modules by running the following command (taking the Ubuntu/Debian system as an example):
sudo a2enmod proxy sudo a2enmod proxy_wstunnel
Restart Apache after enabled:
sudo systemctl restart apache2
Configure reverse proxy support for WebSocket
To get WebSocket to work properly, you need to pay special attention to the request header and protocol upgrade section. A basic configuration example is as follows:
<VirtualHost *:80> ProxyPreserveHost On ProxyPass /ws/ ws://backend-server/ ProxyPassReverse /ws/ http://backend-server/ # If it is HTTPS, use wss:// and the corresponding ProxyPass setting</VirtualHost>
Here are a few key points to note:
- Use a URL starting with
ws://
orwss://
to specify the destination address. - Make sure that the path matches correctly, such as the front-end access
/ws/xxx
, and the back-end must be able to handle the corresponding paths. - If you have both HTTP and WebSocket interfaces, you can map the WebSocket path separately to avoid interfering with other services.
Handle FAQs
Request denied or connection interrupted
This is usually caused by not properly setting the Upgrade and Connection request headers. You can add the following content to the configuration to force the delivery of these headers:
RequestHeader set Upgrade "websocket" env=HTTP_UPGRADE RequestHeader set Connection "upgrade" env=HTTP_CONNECTION
This way Apache will correctly forward the WebSocket protocol switching request to the backend.
Pay attention to configuration when using SSL/TLS
If you are using HTTPS and WSS (WebSocket Secure), you need to make sure that the SSL is configured correctly and that Apache's ProxyPass points to wss://
address. Additionally, the SSL certificate must be valid, otherwise the browser may be disconnected directly.
Testing and debugging methods
The easiest way to test whether WebSocket works properly is to initiate a connection using a browser console or some WebSocket client tool such as wscat or Postman.
In addition, Apache's log files (usually in /var/log/apache2/access.log
and /var/log/apache2/error.log
) can help troubleshoot the cause of connection failure.
Basically that's it. WebSocket is prone to problems in reverse proxy environments mainly focuses on protocol upgrades and path mapping. As long as these two points are configured properly, the rest will be left to the backend to handle.
The above is the detailed content of How to handle WebSocket connections with mod_proxy_wstunnel?. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undress AI Tool
Undress images for free

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

When encountering an "invalidcommand" error, first you must locate the error position and check whether the syntax is correct. 1. Check the file name and line number in the error message, open the corresponding file to check spelling, uppercase, uppercase, redundant or missing characters and Chinese symbols; 2. Check the official document to confirm the legality of the command, applicable environment and version support; 3. Use configuration detection tools (such as nginx-t, shellcheck) to assist in troubleshooting; 4. Check hidden characters or indentation issues, and use cat-A or editor to display blank characters to verify the consistency of the format. Follow these steps to check one by one, and problems can usually be quickly found and fixed.

The most direct way to record the request processing time is to record the timestamps and calculate the difference at the beginning and end of the request. Specific methods include: 1. Manually record in the code, such as Node.js uses time.time() to record the start and end times through process.hrtime() or PythonFlask; 2. Use framework middleware or built-in functions, such as Express's morgan, Django custom middleware, or Nginx's $request_time, etc., to achieve logging without modifying the code; 3. Combine APM tools such as NewRelic, Datadog or OpenTelemetry for in-depth performance analysis, or use Ch

To enable sticky sessions, you need to configure mod_proxy_balancer and related modules and set the correct sessioncookie. 1. Enable the necessary modules: mod_proxy, mod_proxy_http, mod_proxy_balancer, mod_lbmethod_byrequests and optional mod_session; 2. Configure the virtual host file, define the BalancerMember and specify the route identifier, and use ProxySet to set the lbmethod load algorithm and stickysession parameters; 3. Set the correct cookie name such as JSE according to the backend application type

Apachenotstartingafteraconfigurationchangeisusuallycausedbysyntaxerrors,misconfigurations,orruntimeissues.(1)First,checktheconfigurationsyntaxusingapachectlconfigtestorhttpd-t,whichwillidentifyanytypos,incorrectpaths,orunclosedblockslikeor.(2)Next,re

The MPM selection of ApacheHTTPServer depends on performance requirements and module compatibility. 1.Prefork runs in a multi-process mode, with high stability but high memory consumption, and is suitable for scenarios where non-thread-safe modules such as mod_php are used; 2. Worker adopts a multi-threaded hybrid model, with higher memory efficiency, and is suitable for environments where modules are thread-safe and require concurrent processing; 3. Event optimizes connection management based on Worker, especially suitable for modern architectures with high traffic and support asynchronous operations. Selecting the most suitable MPM according to actual application can balance resource occupation and service stability.

The easiest way to enable or disable Apache modules is to use the a2enmod and a2dismod commands. 1.a2enmod enables modules by creating a symbolic link from mods-available to mods-enabled; 2.a2dismod disables modules by deleting this link; 3. When enabling modules, you need to run sudoa2enmod [module name] and restart Apache; 4. When disabling modules, use sudoa2dismod [module name] and restart the service; 5. Pay attention to the accuracy and dependencies of the module names to avoid configuration errors; 6. After modification, you should test the configuration and clean old references to prevent problems; 7. These commands are only applicable to Debian/Ubu

Using .htaccess files can negatively affect web server performance, especially in cases of high frequency access or improper configuration. The main problem is that every request reads the .htaccess file, which adds additional overhead compared to directives that directly write to the main configuration file (such as httpd.conf). Specifically manifested as: 1. Apache will look for the .htaccess file in the directory in each request, and search even if it does not exist, resulting in more disk I/O and affecting the response speed; 2. The rules in htaccess will be re-parsed and executed every time they request, including URL rewriting, authentication, redirection, etc., while the instructions in the main configuration file will only start or reload Apache.

The steps for Apache to modify the default port to 8080 are as follows: 1. Edit the Apache configuration file (such as /etc/apache2/ports.conf or /etc/httpd/conf/httpd.conf), and change Listen80 to Listen8080; 2. Modify the tag port in all virtual host configurations to 8080 to ensure that it is consistent with the listening port; 3. Check and open the support of the 8080 port by firewall (such as ufw and firewalld); 4. If SELinux or AppArmor is enabled, you need to set to allow Apache to use non-standard ports; 5. Restart the Apache service to make the configuration take effect; 6. Browser access
