Appending Path to Host Haproxy

I am new to haproxy (actually proxy'ing in general) and I can't figure out how to add a path to my backend. I have my backend defined as:

server server1 ns.foo.com:7170 check

I want to add /web such that the request is directed to .

Thanks, Mark

2 Answers

What you need is HTTP rewriting

Adding this to your backend should solve your problem:

acl p_root path -i /
http-request set-path /web if p_root
1

If you would like to send a request coming in a given port to a specific path, you can modify the request either in the frontend or backend configuration by specifying a http-request rule using the set-path action

For example if you would like to send any request to a /web then you should write

http-request set-path /web

into your backend configuration

Otherwise if you would like to prepend the incoming request path with /web (so for example
localhost:[port]/somepath
should go to
serverhost:[serverport]/web/somepath) as Mawardy asked.

Then you should also use the %[path] variable like this

http-request set-path /web/%[path]

I have created a proof of concept of a spring server running with 2 instances in docker which are loadbalanced with a HA proxy in docker that also modifies the path depending on which server won the loadbalancing. For this the ha proxy is configured to loadbalance between its own frontends which has their own backend with their modified path

The configuration looks like this

defaults
  retries           3
  maxconn           20
  timeout connect   5s
  timeout client    6s
  timeout server    6s

frontend http-in
  bind *:9002
  mode http
  use_backend proxy-backend

backend proxy-backend
  balance roundrobin
  mode http
  option forwardfor
  http-response set-header X-Forwarded-Port %[dst_port]
  http-response set-header X-ProxyServer %s
  server proxy-server-1 localhost:9000
  server proxy-server-2 localhost:9001

frontend proxy-in1
  bind *:9000
  mode http
  use_backend poc-server2
frontend http-in2
  bind *:9001
  mode http
  use_backend poc-server1

backend poc-server1
  mode http
  http-response set-header X-Server %s
  http-request set-path /api/one/%[path]
  server poc-server-1 proxypochost1:9000

backend poc-server2
  mode http
  http-response set-header X-Server %s
  http-request set-path /api/two/%[path]
  server poc-server-2 proxypochost2:9001

For more information you can check the whole project with some additional information in its readme here: ha-proxy-poc

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Sarah Jenkins

Sarah Jenkins

Senior Technology Editor & AI Specialist

Sarah Jenkins is a veteran tech journalist with over 12 years of experience covering artificial intelligence, mobile innovations, and digital ethics. Her insights have appeared in leading technology publications worldwide.

Share this article
Twitter Facebook Pinterest