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
│
└──► TargetThe 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
| Option | Type | Default | Description |
|---|---|---|---|
enabled | bool | false | Enable WebSocket transport |
mode | string | "mixed" | Connection mode |
path | string | "/ws" | WebSocket endpoint path |
host | string | optional | Expected Host header value |
listen | string | optional | Separate listen address for WebSocket |
max_frame_bytes | int | 16384 | Maximum 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/wsuse 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 portThis 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
- Set up a DNS record pointing to your server
- Enable Cloudflare proxy (orange cloud)
- Configure a WebSocket route in Cloudflare
- 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.