Please note that “rewrite” can mean a lot of things when it comes to HTTP. Please be more specific, and give a concrete example in terms of “this is the original browser request, this is how it should actually be reaching the backend server, and this is how the reply body should be changed (if applicable)”.
Do you need to just replace the Host request header? If so use http-request set-header Host www.domain2.com.
I would also point you to a previous discussion about this topic which discusses a few options:
There is a requirement to access our app using 'newsub.domain2.com’. So we have configured a CNAME record to forward all requests from 'newsub.domain2.com’ to sub.domain1.com. The requests reach the LB, but doesn’t work since the application only understands sub.domain1.com.
First of all, understand that DNS CNAME’s are not redirects. They are just one-way aliases. It’s just like saying <<when I say “Deutchland”, I actually mean “Germany”>>.
Therefore when your DNS client resolves that CNAME, it behaves just like you would have put a normal A record with the proper IP.
As hinted before, there isn’t a “one solution” to your problem, but it depends a lot on how your application behaves. Just try that http-request set-header Host statement as I’ve previously described. If it works then it should be enough.
However, many web applications “know” that they should run on sub.domain1.com (by having this hardcoded in the responses or code), therefore even though from the HTTP protocol point of view they work, they don’t properly work.
I would strongly advise to contact the developers and see if you can configure the application to work properly with the new domain without these “tricks”.
(To be clear: this is not an HAProxy limitation, but of the way the “web” works, especially browsers and web application platforms.)