HAProxy – Perform multiple rewrites based on conditions

access-control-listhaproxyrewrite

I am trying to rewrite a URI as well as a host header based on some conditions. Here is an example of what I'm trying to accomplish:

I request http://sub1.example.com/test/files/other

if hdr_beg(Host) sub1.example.com and path_beg /test
    rewrite host header to sub2.example.com
    rewrite URI to /files/other (in other words, remove test from the URI)

The end result should point to sub2.example.com/files/other without the user being aware.

I have tried the following configuration:

acl host_beg_sub1 hdr_beg(Host) sub1.example.com
acl path_beg_test path_beg /test
rewrite host header if host_beg_sub1 path_beg_test
rewrite URI if host_beg_sub1 path_beg_test

Obviously, this doesn't work as expected since the second rewrite won't fire after the host header has been modified.

I cannot rewrite without a condition since there is other traffic whose URI might begin with test.

Thanks in advance!

Best Answer

If you want to make a bunch of replacements, you might want to consider putting them in a backend.

frontend
    acl host_beg_sub1 hdr_beg(Host) sub1.example.com
    acl path_beg_test path_beg /test
    use_backend sub2redirect if host_beg_sub1 path_beg_test 

backend
    reqirep ^Host:\ sub1.example.com   Host:\ sub2.example.com
    reqirep ...url rewriting 
    server ...
Related Topic