用haproxy实现nginx的proxy_pass转发功能

 公司的网站有个需求,主站点上有两个URL,没有在本地nginx上配置,而是在另一台主机的nginx上配置的站点。如果使用nginx作为反向代理,可以使用proxy_pass指令转发对这两个URL的请求到另一台主机。

    那么在haproxy作为反向代理的情况下,该如何配置呢?下边来说一下。
 
用haproxy实现nginx的proxy_pass转发功能
1. nginx的主机上为了安全,关闭了空主机头
server {
       listen 80 default;
       return 500;
}
 
2.haproxy的配置
frontend main
    bind *:80
    acl web hdr(host) -i www.abc.com
    acl webapp path_beg -i /investApp/ln/
    acl investapp path_beg -i /investApp/
    use_backend webapp_bk if web webapp
    use_backend investapp_bk if web investapp
    use_backend webserver if web
    default_backend webserver
 
backend webserver
    mode http
    balance roundrobin
    server nginx01 192.168.27.131:80
 
backend webapp_bk
    http-request set-header Host img.abc.com
    reqirep ^([^ :]*) /investApp/ln/(.*)  1 /webApp/ln/2
    server nginx02 192.168.27.132:80
 
backend investapp_bk
    http-request set-header Host img.abc.com
    server 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 webapp
    use_backend investapp_bk if web investapp
    use_backend webserver if web
 
因为严格限制了主机头,所以转发到nginx02上的request必须使用正确的img.abc.com的主机头,另外还需要做路径替换。
backend webapp_bk
    http-request set-header Host img.abc.com
    reqirep ^([^ :]*) /investApp/ln/(.*)  1 /webApp/ln/2
 
reqirep用来匹配HTTP请求,“GET /investApp/ln/ HTTP/1.1 ”,然后将前后两部分保存到变量中,在后边引用。
 
参考文档:
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/
原文地址:https://www.cnblogs.com/larry-luo/p/10135925.html