Favourite Videos

Loading...

Friday, March 18, 2011

User-Agent based redirect in haproxy

We've been using haproxy as our loadbalancer for quite sometime now  and I'd say it's been more than wonderful. We've been using it for serving around 2 million page-views per day and it's been pretty good at handling that kind of HTTP traffic. Recently we decided to launch our mobile site and the idea was to allow users to visit our website through normal URL that we use for our website, however upon detection of user-agent we wanted to rewrite the URL to something else. We knew that haproxy was able to parse and identify HTTP Headers and hence we were pretty positive about the idea of using haproxy to do the redirection, however to our surprise, haproxy 1.3 doesn't allow for conditional rewrites and the worst aspect of it is that it doesn't even complain about implementing conditional rewrites, instead it silently ignores the condition and implements the rewrite to every request.

 So we finally decided to migrate to haproxy 1.4 and we use following configuration to setup conditional redirect:

1) Create new ACL to identifiy user-agent:

acl mobile_user_agent hdr_sub(User-Agent) -i iphone

2) We didn't want to redirect any requests for .css, .js, .bmp, .jpg, .png, .jpeg, .gif and .ico so created a new ACL


acl is_static_file url_reg .*\.(css|js)\?[0-9.]+
acl is_static_img url_reg .*\.(png|bmp|jpg|jpeg|gif|ico)\?[0-9a-z.]+
acl is_static url_reg .*\.(css|js|png|bmp|jpg|jpeg|gif|ico)

3) If request was for /mobile/* we didn't want to redirect so yet another ACL :)

acl is_mobile url_reg ^\/mobile.*

4) Do a URL rewrite as follows:

reqrep ^([^\ ]*)\ /(.*)   \1\ /mobile/\2 if iphone !is_static_file !is_static_img !is_static !is_mobile

So now any request coming from a mobile device for any thing other than .css, .js, .png, .gif, .bmp, .jpg, .jpeg, ico will be redirected to /mobile/.

So a request like www.abc.com/pqr will become www.abc.com/mobile/pqr !


0 comments: