Trojan Rust

WebSocket Transport

Configuring WebSocket transport for CDN compatibility

trojan-rs supports WebSocket as an optional transport layer. This wraps the Trojan protocol inside WebSocket frames, enabling the server to operate behind CDNs and reverse proxies that support WebSocket.

How It Works

Client ──WebSocket──► CDN ──WebSocket──► trojan-server

                                              └──► Target

The WebSocket layer does not change the Trojan protocol. It simply provides an additional encapsulation layer. The Trojan header and authentication work the same way.

Configuration

[websocket]
enabled = true
mode = "mixed"
path = "/ws"

Options

OptionTypeDefaultDescription
enabledboolfalseEnable WebSocket transport
modestring"mixed"Connection mode
pathstring"/ws"WebSocket endpoint path
hoststringoptionalExpected Host header value
listenstringoptionalSeparate listen address for WebSocket
max_frame_bytesint16384Maximum WebSocket frame size

Modes

mixed — Accept both raw TLS and WebSocket connections on the same port. The server detects the protocol automatically.

[websocket]
enabled = true
mode = "mixed"
path = "/ws"

In mixed mode:

  • Connections to wss://server:443/ws use WebSocket transport
  • Direct TLS connections to port 443 use raw Trojan protocol

only — Accept only WebSocket connections. Raw TLS Trojan connections are rejected.

[websocket]
enabled = true
mode = "only"
path = "/ws"

Split Mode

Use a separate port for WebSocket:

[server]
listen = "0.0.0.0:443"

[websocket]
enabled = true
mode = "mixed"
path = "/ws"
listen = "0.0.0.0:8080"             # WebSocket on separate port

This is useful when placing the WebSocket port behind a CDN while keeping the raw TLS port for direct connections.

Host Header Validation

Restrict WebSocket connections to a specific Host header:

[websocket]
enabled = true
host = "cdn.example.com"

Requests with a different Host header are rejected.

CDN Setup

Cloudflare

  1. Set up a DNS record pointing to your server
  2. Enable Cloudflare proxy (orange cloud)
  3. Configure a WebSocket route in Cloudflare
  4. On the server:
[websocket]
enabled = true
mode = "only"
path = "/ws"
host = "your-domain.example.com"

Generic Reverse Proxy (nginx)

location /ws {
    proxy_pass http://127.0.0.1:8080;
    proxy_http_version 1.1;
    proxy_set_header Upgrade $http_upgrade;
    proxy_set_header Connection "upgrade";
    proxy_set_header Host $host;
}

Client Configuration

When connecting through WebSocket, configure the client to use WebSocket transport. The specifics depend on the client implementation being used.

On this page