Haproxy 301 URL redirect on query string condition

301-redirecthaproxyrewrite

Using Haproxy 1.5.12 running on Ubuntu 12.04

My website gets a lot of requests like this one:

http://www.example.com/foo/bar/mypage.php?gallery=&position=3

the correct URL should be:

http://www.example.com/foo/bar/mypage.php?gallery=photogallery&position=3

I've been successful in rewriting requests to the correct URL, but I would also like to issue a 301 redirect to clients.

Following this post: redirect rewritten url using haproxy I tried:

acl fix_gallery url_sub gallery=&
reqrep (.*)gallery=&(.*) \1gallery=photogallery&\2
redirect prefix / code 301 if fix_gallery

Trying to be creative I've tried:

acl fix_gallery url_reg (.*)gallery=&(.*)
acl fix_gallery urlp_reg(gallery) -m str ""
acl fix_gallery urlp_reg(gallery) -m len 0

and many more.
But nothing seems to work, so I'm obviously missing something.

Any suggestions?

Thanks

Best Answer

You can achieve what you're looking for using 3 lines of config that leverage the http-request keyword.

The first sets a dummy header that we'll use in the following two.

http-request set-header X-Location-Path %[capture.req.uri] if fix_gallery

The second performs the substitution you need to fix the URL query.

http-request replace-header X-Location-Path (.*)gallery=&(.*) \1gallery=photogallery&\2 if fix_gallery

The final line does the direction to the changed URL.

http-request redirect location http://www.example.com/%[hdr(X-Location-Path)] if fix_gallery

This works if you only have one domain, but it's possible to build http-request redirect lines that will work with any domain and scheme.

http-request redirect location https://%[hdr(host)]/%[hdr(X-Location-Path)] if fix_gallery { ssl_fc }
http-request redirect location http://%[hdr(host)]/%[hdr(X-Location-Path)] if fix_gallery !{ ssl_fc }
Related Topic