Tuesday, April 03, 2018

URL redirect with haproxy


I have following requests
GET/POST http://10.0.0.1:8081/foo/abc/pqr
GET/POST http://10.0.0.1:8081/bar/xyz/tuv

Depending on /foo or /bar i need to send them to different  backends let say fooServer and barServeras follows


GET/POST http://10.0.0.1:8080/abc/pqr
GET/POST http://10.0.0.1:8585/xyz/tuv


Solution
Use haproxy or nginx to ulr redirect, I have tried nginx and this time i want to try haproxy therefore this post is based on haproxy

Install haproxy (on Mac), Configure and Run

1. install brew 
     see https://brew.sh/
2. brew install haproxy
3. Configure haproxy.cfg 
     vim /usr/local/etc/haproxy.cfg
4. Start haproxy
     To have launchd start haproxy now and restart at login:
        brew services start haproxy
     Or, if you don't want/need a background service you can just run:
        haproxy -f /usr/local/etc/haproxy.cfg


Note that I want to replace the /foo and /bar parts from the original url
Thanks to the solution at https://github.com/rancher/rancher/issues/1701#issuecomment-275112038
it was not that hard

Here is the haproxy.cfg file


global
        maxconn 72000
        daemon

defaults
        mode    http
        timeout connect 4000ms
        timeout client 60000ms
        timeout server 30000ms

listen stats
    bind 10.0.0.1:9090
    mode http
    stats enable
    stats hide-version
    stats realm Haproxy\ Statistics
    stats uri /
    stats auth admin:admin

frontend my_frontend
    bind 10.0.0.1:8081
    acl is_foo path_beg /foo
    use_backend foo_be if is_foo
    acl is_bar path_beg /bar
    use_backend bar_be if is_bar

backend foo_be
    balance roundrobin
    cookie SERVERID insert
    option httpclose
    option forwardfor
    reqrep ^([^\ :]*)\ /foo/(.*)     \1\ /\2
    server fooServer 10.0.0.1:8080  cookie fooServer

backend bar_be
    balance roundrobin
    cookie SERVERID insert
    option httpclose
    option forwardfor
    reqrep ^([^\ :]*)\ /bar/(.*)     \1\ /\2
    server barServer 10.0.0.1:8585  cookie barServer


Note that i wanted to disable the http check, therefore that config is not added