Haproxy change part of url

With HAProxy 1.5 : use a temporary header to build a 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 X-Rewrite unchanged
http-request add-header X-REWRITE %[url] if { path_beg /old_path }

# Change the X-REWRITE header to contain out new path
http-request replace-header X-REWRITE ^/old_path(/.*)?$ /new_path\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, use the regsub filter

http-request redirect code 301 location http://%[hdr(host)]%[url,regsub(^/old_path,/new_path,)] if { path_beg /old_path }

source among other useful configuration snippets

More information is available in the HAProxy documentation for the regsub keyword.


You are confusing url redirection with url rewriting to the backend.

Should you even want to rewrite, then according to the haproxy 1.6 documentation :

  • "set-path" rewrites the request path with the result of the evaluation of format string . The query string, if any, is left intact.

So the correct configuration in that case would be :

acl old_name path_dir -i /old_name
http-request set-path /new_name if old_name

To redirect the user :

redirect location /new_name if old_name

For anyone trying to make changes from uri to REST API, do not use the http-request redirect location because the header data is lost. Use http-request set-uri.

http-request set-uri% [url,regsub(^/old,/new,)] if { path_beg /old }

Tags:

Haproxy