公司的网站有个需求,主站点上有两个URL,没有在本地nginx上配置,而是在另一台主机的nginx上配置的站点。如果使用nginx作为反向代理,可以使用proxy_pass指令转发对这两个URL的请求到另一台主机。
那么在haproxy作为反向代理的情况下,该如何配置呢?下边来说一下。
server {listen 80 default;return 500;}
2.haproxy的配置
frontend mainbind *:80acl web hdr(host) -i www.abc.comacl webapp path_beg -i /investApp/ln/acl investapp path_beg -i /investApp/use_backend webapp_bk if web webappuse_backend investapp_bk if web investappuse_backend webserver if webdefault_backend webserverbackend webservermode httpbalance roundrobinserver nginx01 192.168.27.131:80backend webapp_bkhttp-request set-header Host img.abc.comreqirep ^([^\ :]*)\ /investApp/ln/(.*) \1\ /webApp/ln/\2server nginx02 192.168.27.132:80backend investapp_bkhttp-request set-header Host img.abc.comserver nginx02 192.168.27.132:80
这里的重点配置有几处:
acl web hdr(host) -i
www.abc.com
acl webapp path_beg -i
/investApp/ln/
acl investapp path_beg
-i /investApp/
这里声明了3条acl
acl web匹配 www.abc.com主机头
acl webapp匹配路径: /investApp/ln/
acl investapp匹配路径: /investApp/
可以看到,investapp匹配的路径包含了webapp匹配的路径。
因为haproxy的acl是按照顺序执行,第一个acl匹配到以后就不再向下遍历,所以我们必须把acl webapp放到acl
investapp之前执行,否则acl webapp永远也不会被执行到。即如下配置:
use_backend webapp_bk if web webappuse_backend investapp_bk if web investappuse_backend webserver if web
因为严格限制了主机头,所以转发到nginx02上的request必须使用正确的img.abc.com的主机头,另外还需要做路径替换。
backend webapp_bkhttp-request set-header Host img.abc.comreqirep ^([^\ :]*)\ /investApp/ln/(.*) \1\ /webApp/ln/\2
参考文档:
https://blog.haproxy.com/2014/04/28/howto-write-apache-proxypass-rules-in-haproxy/
http://thread.gmane.org/gmane.comp.web.haproxy/4598
http://serverfault.com/questions/647479/haproxy-use-backend-match-order
http://stackoverflow.com/questions/22219479/haproxy-backend-with-subdirectory-subpath-subfolder
http://stackoverflow.com/questions/30256571/haproxy-path-to-host-path
https://linux-tips.com/t/routing-urls-to-different-backends-in-haproxy/24
https://www.digitalocean.com/community/tutorials/how-to-use-haproxy-as-a-layer-7-load-balancer-for-wordpress-and-nginx-on-ubuntu-14-04
https://www.claudiokuenzler.com/blog/554/haproxy-forward-based-on-string-in-url-combine-existing-acl
http://blog.defsdoor.org/a-note-on-haproxys-acl-matching/