apache2 - redirect http:// and ws:// with proxy module (proxy_wstunnel)
In this article, we are going to look at the problem of how to redirect domain traffic that uses both WebSockets and HTTP from one address to another with apache2.
In-network we can find a lot of examples that do not work because of redirection rules priority. This example was tested on Debian but can be used with other operating systems too.
Important:
Someimtes working with WebSockets it is important to close not used sockets - do not closing may lead to open ports overflowing in a longer time!
Deprecation:
Since Apache HTTP Server 2.4.47, protocol Upgrade (tunneling) can be better handled by
mod_proxy_http
.See Protocol Upgrade.
To solve the problem it is necessary to execute the following steps:
1. Enable proxy modules
To make redirection possible it is necessary to enable proxy modules at first.
Note: this approach was tested with apache 2.4.
Execute in terminal following commands to enable apache2 modules:
a2enmod rewrite
a2enmod proxy
a2enmod proxy_http
a2enmod proxy_wstunnel
2. Create ViarutaServer configuration
Create new or open one of the files located in /etc/apache2/sites-enabled/
directory and put following rule inside:
<VirtualHost *:80>
ServerName mydomain.com
RewriteEngine On
RewriteCond %{HTTP:Upgrade} =websocket [NC]
RewriteRule /(.*) ws://localhost:8080/$1 [P,L]
RewriteCond %{HTTP:Upgrade} !=websocket [NC]
RewriteRule /(.*) http://localhost:8080/$1 [P,L]
ProxyPassReverse / http://localhost:8080/
</VirtualHost>
Note: this configuration redirects all trafic from
mydomain.com
address (port80
) tolocalhost:8080
address includingws://
andhttp://
.
3. Restart apache2 server
Run followin command to restart apache2 serwer:
systemctl restart apache2
Note: replace command with other if non Debian operating system is used.
References
Alternative titles
- apache2 - redirect address with proxy module (proxy_wstunnel)
- apache2 - redirect domain with proxy module (proxy_wstunnel)
- apache2 - virtual serwer with websocket proxy module
- apache2 - virtual serwer with ws proxy module
- apache2 - configure mod_proxy_wstunnel
- apache2 - redirect http and ws with proxy module (proxy_wstunnel)
- apache2 - redirect websocket apache2 (proxy_wstunnel)