What's the more elegant way to do this? (removing prefix/suffix in a variable)

1. The problem I’m having:

I’m trying to extract a subdomain from a domain using this directive:

map {host} {database} {
    ~^(.*)\.odoo19e\.internal\.net$ "$1"
    default "none"
}

And it seems to work fine, but is there a better way to remove a prefix/suffix in a variable?

I also use the similar approach to host a PHP application under a subdirectory:

handle_path /app* {
    map {http.request.orig_uri} {stripped_uri} {
        ~^/app(.*) "$1"
        default "none"
    }

    root * /php/app/public
    php_fastcgi 127.0.0.1:9000 {
        env REQUEST_URI {stripped_uri}
    }
    file_server
}

We used this because handle_path (or uri strip_prefix) removes the query params in {uri}, and when it’s passed to PHP-FPM, our app expects query params to still exists in $_SERVER['REQUEST_URI'] instead of using $_SERVER['QUERY_STRING'] (bad practice, we know, but it’s a legacy app).

That being said, is there a better way to remove a prefix/suffix in a variable?

2. Error messages and/or full log output:

N/A

3. Caddy version:

v2.9.1

4. How I installed and ran Caddy:

a. System environment:

N/A

b. Command:

N/A

c. Service/unit/compose file:

N/A

d. My complete Caddy config:

N/A

5. Links to relevant resources:

N/A

Your solution is already quite elegant. You may also want to try something like this (adjust it to your setup):

:80 {

	@app_uri vars_regexp {uri} ^/app(/.*)
	vars @app_uri stripped_uri {re.app_uri.1}

	handle_path /app/* {
		respond "Stripped URI: {vars.stripped_uri}"
	}
}
$ curl http://localhost/app/
Stripped URI: /
$ curl http://localhost/app/test
Stripped URI: /test
$ curl http://localhost/app/test/foo?bar
Stripped URI: /test/foo?bar
1 Like

That said, in your particular case, you might as well just pass the {uri} variable to PHP-FPM once you’re inside the handle_path block. It’s already stripped:

:80 {
	
	handle_path /app/* {
		respond <<EOF
			Original URI: {http.request.orig_uri}
			Stripped URI: {uri}
			EOF
	}
}
$ curl http://localhost/app/test/foo?bar
Original URI: /app/test/foo?bar
Stripped URI: /test/foo?bar
1 Like