Remapping URLs based on map file, with precedence

Hi, I am trying to remap a number of directories on my site based on a map file, preserving any trailing components in the path. So if I have the following map file:

/dir1/ /newdir/

and get a request for https://example.org/dir1/foo.txt I would like the request to be served from http://example.org/newdir/foo.txt (not redirected, just silently rewritten)

One difficulty is that the map file may have overlapping entries, where /dir1/ is mapped one place but /dir1/path2/ is mapped elsewhere, in which case I would like /dir1/path2/ to have precedence and the entry for /dir1/ to be ignored. (i.e. the match with the most path components should have highest precedence)

I have been trying to figure out how to implement this and it’s proving to be quite difficult, possibly because I have limited experience with haproxy.

Does anyone have an idea how I might implement something like this? I could share some config snippets if that would help but I really have nothing even close to working.

Part of the issue is that regsub doesn’t allow backreferences so maybe I would need to use reqrep which does, but it seems to be deprecated. Maybe map_regm would be useful, but I don’t know how to get my desired longest-path-has-precedence.

My map file is generated using a separate process and I could consider splitting it into multiple maps if that helps with the precedence issue, but I am hoping that won’t be necessary since the map file is updated during runtime using commands over the socket and I would rather not make that process more complicated.