HAProxy community

Http redirect /foo/bar?a=b to /foo/bar/?a=b

Hello,

I’m trying to figure out what is the good way to redirect requests to add a trailing slash, while preserving the query string.

Found this in the documentation in : http://cbonte.github.io/haproxy-dconv/2.1/configuration.html#4.2-redirect%20prefix

First, it seems there is an error in the following example :

acl missing_slash path_reg ^/article/[^/]*$
redirect code 301 prefix / drop-query append-slash if missing_slash

it think there is a extra / that should be removed like this :

acl missing_slash path_reg ^/article[^/]*$
redirect code 301 prefix / drop-query append-slash if missing_slash

So that’s working (2nd version), but in my case I’d like to preserve the query, but if I remove ‘drop-query’, the append-slash is not behaving right.
I get redirected to something like /article?foo=bar/.

So in the documentation it states that we should only use append-slash in conjunction with drop-query.

But then, what’s the right way to redirect, adding a missing trailing slash on the path, preserving the querystring, and with a config that works for both HTTP1.1 and HTTP2 ?

Thanks!

Olivier

I can do something like

http-request redirect code 301 location /foo/bar/?%[query] if { path_reg ^/foo/bar[^/]*$ }

But then it adds a ? when query is empty, I’d like to avoid that.
How can I have a conditional ‘?’ ?

You can check whether or not a query is present with query -m found

So I suggest:

acl request_has_query query -m found
http-request redirect code 301 location /foo/bar/?%[query] if request_has_query { path_reg ^/foo/bar[^/]*$ }
http-request redirect code 301 location /foo/bar/ if ! request_has_query { path_reg ^/foo/bar[^/]*$ }

you can also use %HQ without worrying about query being populated or not.

http-request redirect code 301 location /foo/bar/%HQ if { path_reg ^/foo/bar[^/]*$ }