Reverse HTTP & Websocket Proxy in Apache

The following is an Apache2 virtual hosts configuration last used in Debian 10. This configuration is able to handle normal HTTPS and Websocket traffic on the same path, with normal HTTP traffic also being proxied (does not redirect to HTTPS).

<VirtualHost *:80>
    ServerName example.com

    CustomLog ${APACHE_LOG_DIR}/access.log combined

    ProxyPreserveHost On
    ProxyPass / http://<host of HTTP server>:80/
    ProxyPassReverse / http://<host of HTTP server>:80/
</VirtualHost>

<VirtualHost *:443>
    ServerName example.com

    CustomLog ${APACHE_LOG_DIR}/access.log combined

    SSLEngine on
    SSLCertificateFile <path to your full certificate chain>
    SSLCertificateKeyFile <path to your private key>

    ProxyPreserveHost On
    ProxyRequests off
    ProxyPass /.wellknown !
    ProxyVia On
    RewriteEngine On
    RewriteCond %{HTTP:Connection} Upgrade [NC]
    RewriteCond %{HTTP:Upgrade} websocket [NC]
    # change the port to your websockify port
    RewriteRule / ws://<host of websocket server>:<websocket port on websocket server> [P,L]

    ProxyPass / http://<host of HTTP server>:80/
    ProxyPassReverse / http://<host of HTTP server>:80/
</VirtualHost>

The following packages needed to be installed:

  • python-mod-pywebsocket
  • apache2

The following Apache2 module needs to be enabled:

  • proxy_wstunnel