On Aug 7, 2014, at 3:17 PM, O'Shaughnessy Evans <[email protected]> wrote:
> Hello. I'm having trouble working out a way to rewrite a request URI and do a
> redirect with haproxy.
>
> I have rules like this:
>
> http-request add-header X-Forwarded-Proto http if !{ ssl_fc }
> http-request add-header X-Forwarded-Proto https if { ssl_fc }
> http-request redirect prefix
> %[hdr(X-Forwarded-Proto)]://%[capture.req.uri,map_reg(/usr/local/etc/haproxy/cdn-hosts.lst)]
> drop-query
> reqrep ^([^\ ]*)\ /cdn/([^/]*)/(.*) \1\ /\3
>
> In cdn-hosts.lst, I have this:
>
> /[^/]+/A/.+ cdnA
> /[^/]+/B/.+ cdnB
>
> ...
> So is there another way to perform this kind of magic with haproxy? Right now
> I have dozens of static rules where I use reqrep and ACLs, listing each CDN
> endpoint. I'd like to get away from that and limit my maintenance to a map
> file.
>
> I appreciate any insight. Thanks.
Hello, all. I just wanted to report that I solved this. I thought the solution
might be useful to others.
Haproxy 1.5.1 and newer (I think) support "http-request replace-header". So I
added a new header, rewrote it, then used the result to issue my redirect. All
of this can be done at the stage where "http-request" does its processing. The
result looks like this:
http-request add-header X-Forwarded-Proto http if
!{ ssl_fc }
http-request add-header X-Forwarded-Proto https if
{ ssl_fc }
http-request set-header X-Location-Host
%[capture.req.uri,map_reg(/usr/local/etc/haproxy/cdn-hosts.lst)]
# if no host was found in the map, fall back to using the original
http-request replace-header X-Location-Host ^$ %[hdr(Host)]
# rewrite the new request URI:
# strip /whatever/alias/ from the beginning of the redirect URI
http-request set-header X-Location-Path %[capture.req.uri]
http-request replace-header X-Location-Path [^/]+/[^/]+/(.*) \1
# redirect to the Location header we built up
http-request redirect location
%[hdr(X-Forwarded-Proto)]://%[hdr(X-Location-Host)]/%[hdr(X-Location-Path)]
drop-query
To Willy and the other haproxy contributors, thanks so much for this software.
I've been using it for 2 years now and the more I use it, the more I've grown
to appreciate it. The improvements in the 1.5 branch are great and have given
me some very nice ways to clean up my configs.