How to restrict paths to WebSocket-only connections in Caddy 2?

I’m trying to restrict specific paths to only accept WebSocket connections in my Caddy 2 server. I have a working configuration for regular HTTP traffic, but I want to modify it to only allow WebSocket connections for certain endpoints.

Current working config:

handle /path* {
  uri strip_prefix /path
  reverse_proxy localhost:3000
}

I want to:

  1. Only allow WebSocket connections to /path
  2. Return 404 for any non-WebSocket requests to these paths
  3. Maintain the WebSocket connection (currently getting Connection: keep-alive instead of upgrade)

I’ve tried various approaches with @websocket matchers and header checks but can’t get it to work. What’s the correct way to restrict paths to WebSocket-only connections in Caddy 2?

This matcher works to match websocket requests (from the docs Request matchers (Caddyfile) — Caddy Documentation):

@websockets `header({'Connection':'*Upgrade*','Upgrade':'websocket'})`

So you can just invert it to match things that aren’t websockets.

@notwebsockets `!header({'Connection':'*Upgrade*','Upgrade':'websocket'})`

Then you can error @notwebsockets 404 or whatever.

2 Likes

This topic was automatically closed 30 days after the last reply. New replies are no longer allowed.