Redirect to remove trailing slash, with query string

What is the best way to write a rule to drop a trailing slash in a redirect, but keep the query string if any?

http-request redirect location %[path,regsub(/$,)] code 301 if {path_end /} 

will remove the trailing slash, but will drop any query string.

http-request redirect location %[path,regsub(/$,)]?%[query] code 301 if {path_end /}

on the other hand, will add a “?” to the end even if there isn’t a query string.

And I don’t think I can use a regsub on the full url because of https://github.com/haproxy/haproxy/issues/200 which prevents me from using a capture group.

ACL it further.

Use the former if there is no query and the latter if there is one.

edit: you can use query -m found:

http-request redirect location %[path,regsub(/$,)] code 301 if ! { path / } { path_end / } ! { query -m found }
http-request redirect location %[path,regsub(/$,)]?%[query] code 301 if ! { path / } { path_end / } { query -m found }

I also added a guard against redirecting from root (/).