How to differentiate http and websockets in caddy file

1. The problem I’m having:

Hello,
I am trying to reverse proxy using caddy. The web server uses http and websockets.
http to serve a webpage and websockets for data exchange.

I am getting the webpage to load securely but websockets is not working when activating widgets on the webpage. I am new to servers & networking.

I think the problem is I don’t know how to let caddy know the difference between the two protocols. If I place a different endpoint in the caddy file for websockets everything on the webpage disappears ie. test.boulderhill.xyz/foo/*

2. Error messages and/or full log output:

I am not getting any error messages but when i activate an action on via the webpage there is no activity in caddy which will normally give me a response code of 200 when things are good.

3. Caddy version:

I am using caddy version 2.73

4. How I installed and ran Caddy:

a. System environment:

linux ubuntu 20.04

b. Command:

caddy run, caddy fmt --overwrite, caddy reload

d. My complete Caddy config:

{
	debug

	http_port 80
	https_port 443
}

test.boulderhill.xyz {
	reverse_proxy / 192.168.1.9:80
}

test.boulderhill.xyz {
	header Connection *Upgrade*
	header Upgrade websocket
	reverse_proxy / 192.168.1.9:81
}

Read about request matchers: Request matchers (Caddyfile) — Caddy Documentation There’s an example in there specifically about matching websocket requests.

You don’t need these, they’re redundant.

Using a / matcher means to match only exactly / and nothing else, so only requests to the root of your site. Remove it to match everything.

You can’t have two site blocks with the same addresses. That’s a logic error.

1 Like

Thanks for the quick response.

So with your help it’s working.

The Caddyfile now looks like this:


{
debug
}

test.boulderhill.xyz {
reverse_proxy / 192.168.1.9:80
}

test.boulderhill.xyz:8081 {
reverse_proxy 192.168.1.9:81
}


I had to open up port 8081 on my router for websocket traffic and change the javascript
in my html file from
Socket = new WebSocket(‘ws://’ + window.location.hostname + ‘:81/’);
to
Socket = new WebSocket(‘wss://’ + window.location.hostname + ‘:8081/’);

The internal url is a microcontroller that interfaces with the physical environment and was
presented to only work over a local network.

I definitely need to learn more about Caddy and how it works.

Thanks for your help

You could just do this:

test.boulderhill.xyz {
	@websockets {
		header Connection *Upgrade*
		header Upgrade    websocket
	}
	reverse_proxy @websockets 192.168.1.9:81

	reverse_proxy 192.168.1.9:80
}

Then you don’t need to override the port, and just do: new WebSocket('wss://' + window.location.hostname);

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