Search code examples
http-redirecthaproxy

HAProxy - Add Trailing Slash


I am working on a project where I need requests destined to a particular page to be routed to a separate backend.

For example, all requests for https://mycooldomain.com will go to backend "A". But, if navigating to https://mycooldomain.com/secretpage I want it to go to backend "B".

Now, I have this working but running into an issue where I need the trailing slash for this to work correctly.

So, I need a way to say if request is https://[whateverhostnameisused]/secretpage redirect to https://[whateverhostnameisused]/secretpage/.

Here is a sample of my config so far:

frontend f_https
    bind *:443 ssl crt cert.pem
    reqadd X-Forwarded-Proto:\ https

    #define hosts
    acl host_a hdr(host) -i a.mycooldomain.com
    acl host_b hdr(host) -i b.mycooldomain.com
    acl host_c hdr(host) -i c.mycooldomain.com

    #custom acls
    acl secret path_beg -i /secretpage

    #Custom redirects

    ##define backend
    use_backend b_secret if secret
    use_backend b_a if host_a
    use_backend b_b if host_b
    use_backend b_c if host_c

    default_backend b_https

backend b_secret
    server secret 192.168.15.15:5575 check

Solution

  • It seems that you are looking for something like this:

    http-request redirect scheme https drop-query append-slash if { path -m str /secretpage }
    

    This should work if applied to either the frontend or the backend.

    http://cbonte.github.io/haproxy-dconv/1.6/configuration.html#4.2-redirect%20scheme

    Specifying the scheme is only necessary because the syntax requires one of location | prefix | scheme, and with the other two options, you have to reassemble the URL yourself in the config.


    Note also that reqadd is not officially deprecated, but the preferred way to add that request header is like this:

    http-request set-header X-Forwarded-Proto https
    

    Note that no : is specified and the space after the header name must not be escaped with \. This accomplishes the same result, but it uses a different code path inside HAProxy, and should be a more efficient operation. You will want to use the the http-request and http-response directives instead of reqxxx and rspxxx where possible, as they are also better suited to more complex manipulations.