Strip_prefix to file_server

1. The problem I’m having:

I need to map everything to a Django/uwsgi reverse proxy except for the media and static files. The problem is the URI needs some modifications before serving the files. Those going to the django/reverse_proxy doesn’t.

The specific cases:
/static/file.png → /home/user1/user1web/user1_static/file.png
/media/files/media.png → /home/user1/user1web/user1_media/files/media.png

2. Error messages and/or full log output:

2024/02/28 17:27:44.963	INFO	using provided configuration	{"config_file": "Caddyfile", "config_adapter": ""}
Error: adapting config using caddyfile: parsing caddyfile tokens for 'route': parsing caddyfile tokens for 'file_server': unknown subdirective 'uri', at Caddyfile:9, at Caddyfile:17
(I've removed the comments and global not related, w.r.t. TLS auths etc,.)

3. Caddy version:

2.7.6

4. How I installed and ran Caddy:

a. System environment:

Debian 11
.deb package

b. Command:

systemctl restart

c. Service/unit/compose file:

d. My complete Caddy config:


user1.site.info {
	route {
		file_server /static/* {
			uri strip_prefix /static
			root /home/user1web/static/user1_static/
		}
		file_server /media/* {
			uri strip_prefix /media
			root /home/user1web/static/user1_media/
		}
		reverse_proxy 127.0.0.1:9000
	}
	log {
		format json
		output file /var/log/caddy/caddy-user1.log {
			roll_keep 30
			roll_size 200M
		}
		level debug
	}
}

5. Links to relevant resources:

Can’t see a place in the path other than after the file_server mather to do the uri strip of prefix

You can’t put arbitrary directives inside file_server, you can only pass options that are documented: file_server (Caddyfile directive) — Caddy Documentation

You should write your config like this, using handle_path to strip the matched prefix (see the docs):

user1.site.info {
	handle_path /static/* {
		root * /home/user1web/static/user1_static
		file_server
	}
	handle_path /media/* {
		root * /home/user1web/static/user1_media
		file_server
	}
	handle {
		reverse_proxy 127.0.0.1:9000
	}

	log {
		format json
		output file /var/log/caddy/caddy-user1.log {
			roll_keep 30
			roll_size 200M
		}
		level debug
	}
}

Keep in mind though, since you’re running Caddy as a systemd service, files in /home are not accessible to the caddy user. You should move the files you want to serve to /srv or /var/www/html instead.

1 Like

Thank you!!!
I only saw the route {} option/directive, didn’t find/saw anything like this you just showed.

system<words>D I can handle/tweak/whack into place for this case, the Caddy config to get the /static stripped off was my problem.

thanks again, will test in the morning

Oh, easy solution:

systemctl edit caddy

and insert:

[Service]
SupplementaryGroups=user1web

and Caddy is started to happily read there :wink:

1 Like

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