Last Updated: February 25, 2016
·
12.83K
· kunik

Redirect all www. domains to non-www with haproxy

Sometimes you have a lot of domains and subdomains routed by single load balancer and you want to ensure, that your users always use domains without www. part.

For example:

www.example.com         -> example.com
www.sub1.example.com -> sub1.example.com
www.sub2.example.com -> sub2.example.com
www.example2.com        -> example2.com

This problem can be solved with three lines of haproxy configuration:

#of course, you can do it not in frontend, but in my case it was
#the best place, cause I wanted to make redirect as soon as possible
frontend http

  #bind, and some other code
  #...

  #catch all domains that begin with 'www.'
  acl host_www      hdr_beg(host) -i www.

  #remove 'www.' part from host name
  reqirep ^Host:\ www.(.*)$ Host:\ \1 if host_www
  #now hostname does not contain 'www.' so we can 
  #redirect to the same url
  redirect code 301 prefix / if host_www

3 Responses
Add your response

This doesn't appear to work, at least in HAProxy 1.5... it appears that the ACL is evaluated each time it's referenced, and on the 2nd reference (redirect), host_www apparently evaluates to false since the reqirep statement has already changed what's in the buffer. (?) I'm curious when the behavior changed, and which version was this tested against?

over 1 year ago ·

Like sqlbot have mentioned it seems like acls are being evalutated on each reference that's why it's not working. I have a dirty workaround for that but at least it's working in haproxy 1.5+

http-request add-header X-Host-Redirect yes if { hdr_beg(host) -i www. }
acl host_redirect hdr_cnt(X-Host-Redirect) eq 1
reqirep ^Host:\ www.(.*)$ Host:\ \1 if host_redirect
redirect scheme https if host_redirect
over 1 year ago ·

@slach That did not end up working for me.

over 1 year ago ·