用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/


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM