Skip to content

Instantly share code, notes, and snippets.

@meineerde
Last active January 19, 2023 02:23
Show Gist options
  • Star 7 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save meineerde/11865802f8338b18f123 to your computer and use it in GitHub Desktop.
Save meineerde/11865802f8338b18f123 to your computer and use it in GitHub Desktop.
HAPROXY: Redirect all requests to a URL starting with /foo to /bar while retaining everything following it
# In HAProxy 1.5, we have to jump through some hops to accomplish a rewrite of a request's path...
# We use a temporary header to build our new path from the existing one in the request
# and then directly perform a redirect
# Clean the request and remove any existing header named X-Rewrite
http-request del-header X-REWRITE
# Copy the full request URL into the X-REWRITE request header unchanged
http-request add-header X-REWRITE %[url] if { path_beg /foo }
# Change the X-REWRITE header to contain our new path
http-request replace-header X-REWRITE ^/foo(/.*)?$ /bar\1 if { hdr_cnt(X-REWRITE) gt 0 }
# Perform the 301 redirect
http-request redirect code 301 location http://%[hdr(host)]%[hdr(X-REWRITE)] if { hdr_cnt(X-REWRITE) gt 0 }
# In HAProxy 1.6, there is the regsub filter we can use here
http-request redirect code 301 location http://%[hdr(host)]%[url,regsub(^/foo,/bar,)] if { path_beg /foo }
@davelpz
Copy link

davelpz commented Dec 5, 2018

This worked great for me. Thanks for posting this.

@patricklbs
Copy link

Hello, I take this post to ask you a question if you could help me it would be super nice.
We have a URL which is accessible via http://example.com/Path and I wish via Haproxy only with an alias that I can call the url without / Path:

Is http://example.com possible? I tried this:

reqrep ^ ([^ \] * \ /)\/[/]?(.*) \ 1Path

But that does not work, thank you for your help!

Patrick.

@afarber
Copy link

afarber commented Sep 28, 2019

Thanks, but this produces ERR_TOO_MANY_REDIRECTS for me with HAProxy 1.5

    http-request del-header X-REWRITE1
    http-request add-header X-REWRITE1 %[url] if { path_beg /words/finished.php }
    http-request replace-header X-REWRITE1 ^/words/finished.php(/.*)?$ /ws/finished\1 if { hdr_cnt(X-REWRITE1) gt 0 }
    http-request redirect code 301 location https://%[hdr(host)]%[hdr(X-REWRITE1)] if { hdr_cnt(X-REWRITE1) gt 0 }

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment