公司的網站有個需求,主站點上有兩個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
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/