Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to proxy forward ttyd using Apache

ttyd is a good web based terminal: https://github.com/tsl0922/ttyd

By default, it will use port 7681, so after successfully configured, I can access terminal from localhost:7681 in browser.

We have web server powered by Apache on port 80, and only this port is open to Internet. So in order to access ttyd, I'd like to set a proxy forwarding localhost/shell to localhost:7681, and I set it in httpd.conf like this:

<VirtualHost *:80>
    ProxyPass /shell http://127.0.0.1:7681/
    ProxyPassReverse /shell http://127.0.0.1:7681/
</VirtualHost>

When I visit localhost/shell, it showed me the ttyd page with "Connection closed" message. It seems the connection is not hold. How to solve this problem?

like image 328
Nick Avatar asked Jun 18 '26 00:06

Nick


1 Answers

The problem here is that you need to proxy two protocols, namely http and ws (WebSocket). Without specific handling for the latter, Apache will (of course) use the former for everything which does not work.

You can observe this behaviour (use of different protocols) if you look at the ttyd log and open http://127.0.0.1:7681/ in the browser. Conversely, with the original two Proxy* directives in place, opening the browser's web console and accessing http://127.0.0.1/shell/ shows that all requests to "[/]ws" fail while ttyd will only log http requests for everything (including "[/]ws").

The following solves this (note that this requires mod_proxy_wstunnel and mod_rewrite):

    RewriteEngine on
    RewriteCond %{HTTP:Upgrade} websocket [NC]
    RewriteCond %{HTTP:Connection} upgrade [NC]
    RewriteRule /shell/?(.*) "ws://127.0.0.1:7681/$1" [P,L]
    ProxyPass /shell/ http://127.0.0.1:7681/
    ProxyPassReverse /shell/ http://127.0.0.1:7681/
like image 79
Markus Ueberall Avatar answered Jun 20 '26 10:06

Markus Ueberall



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!