apache2 - redirect http:// and ws:// with proxy module

11 points
Created by:

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: working with WebSockets it is important to close not used sockets - do not closing may lead to open ports overflowing in a longer time!

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>

  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/

Note: this configuration redirects all trafic from address (port 80) to localhost:8080 address including ws:// and http://.

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.


Native Advertising
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂