常用配置選項:
OPTION 選項:
option httpclose :HAProxy會針對客戶端的第一條請求的返回添加cookie並返回給客戶端,客戶端發送后續請求時會發送
此cookie到HAProxy,HAProxy會針對此cookie分發到上次處理此請求的服務器上,如果服務器不能忽略
此cookie值會影響處理結果。如果避免這種情況配置此選項,防止產生多余的cookie信息。
option forwardfor :如果服務器上的應用程序想記錄發起請求的客戶端的IP地址,需要在HAProxy上配置此選項,這樣
HAProxy會把客戶端的IP信息發送給服務器,在HTTP請求中添加"X-Forwarded-For"字段。
option originalto :如果服務器上的應用程序想記錄發起請求的原目的IP地址,需要在HAProxy上配置此選項,這樣HAProxy
會添加"X-Original-To"字段。
option dontlognull :保證HAProxy不記錄上級負載均衡發送過來的用於檢測狀態沒有數據的心跳包。
BALANCE 選項:
balance source :如果想讓HAProxy按照客戶端的IP地址進行負載均衡策略,即同一IP地址的所有請求都發送到同一服務
器時,需要配置此選項。
balance roundrobin :HAProxy把請求輪流的轉發到每一個服務器上,依據每台服務器的權重,此權重會動態調整。最常
見的默認配置。
COOKIE 選項:
cookie JSESSIONID prefix :如果客戶端只支持一個cookie,並且服務器上的應用程序已經對返回設置了cookie,
HAProxy設置此選項可以改寫應用程序設置的cookie信息,把服務器的信息添加到原cookie中去。
cookie SERVERID indirect :HAProxy會刪除添加的cookie信息,避免此cookie信息發送到服務器。
cookie SERVERID rewrite :
cookie SERVERID insert :
cookie SERVERID insert nocache :
cookie SERVERID insert postonly :
option httpclose
no option httpclose
Enable or disable passive HTTP connection closing 啟用或禁止消極的HTTP連接關閉
May be used in sections : defaults | frontend | listen | backend
yes | yes | yes | yes
Arguments : none
默認的,客戶端與服務端的通訊,HAProxy只做分析、日志和分析每個連接的第一個request。如果設置了 "option
httpclose" , 則會檢查雙向的http頭是否有"Connection: close",如果沒有則自動添加,使每個客戶端或服務端在每次傳輸后,都會主動關閉TCP連接,使HTTP傳輸處於HTTP close模式下。任何 "Connection" 頭如果不是"close",都會被移除。
很少會有服務器不正確的忽略掉頭,即使收到"Connection: close"也不關閉連接,否則就是不兼容HTTP 1.0瀏覽器標准。 如果發生這種情況,可以使用"option forceclose",在服務端響應后主動關閉請求連接。選項 "forceclose"還可以及早釋放服務連接,而不必等到客戶端的應答確認。
這個選項可以設置在frontend或backend上,只要其上可以建立連接。如果同時設置了"option forceclose",那么它比"httpclose"優先。如果同時設置了 "option http-server-close",則會實現"option forceclose"的效果。
option forceclose
no option forceclose
Enable or disable active connection closing after response is transferred. 啟用或禁止response后的主動關閉連接
May be used in sections : defaults | frontend | listen | backend
yes | yes | yes | yes
Arguments : none
有的HTTP服務器收到"option httpclose"設置的"Connection: close",也不會關閉連接,如果客戶端也不關閉,連接會 一直打開,直到超時。這會造成服務器上同一時段內的大量連接,日志中也會顯示較高的全局會話時間。
此時,可以使用 "option forceclose",當完成響應時,立即關閉對外的服務通道。該選項隱式打開httpclose選項。需要注意,該選項允許解析完整的request 和 response,所以可以很快關閉至服務器的連接,比httpclose更早釋放一些資源。
如果同時啟用了"option http-pretend-keepalive",雖然會禁止發送 "Connection: close"頭,但是依然會在整個response被接收后,關閉連接。
option http-server-close
no option http-server-close
Enable or disable HTTP connection closing on the server side 啟用或禁止關閉服務端的HTTP連接
May be used in sections : defaults | frontend | listen | backend
yes | yes | yes | yes
Arguments : none
默認的,客戶端與服務端通訊,haproxy 只是分析、記日志,並處理每個連接的第一個請求。該選項設置server端為HTTP 連接關閉模式,並支持客戶端為HTTP keep-alive的pipelining模式。提供了最低的客戶端延遲和最快的服務端會話重用,以節省服務資源,類似"option forceclose"。還允許無keepalive能力的服務端在keep-alive模式下為客戶端提供服務,但是需要符合 RFC2616。需要注意的是,有些服務器遇到"Connection: close" 時並不總是執行關閉,那么keep-alive 則無法使用,解決方法是啟用 "option http-pretend-keepalive".
目前,日志無法指明請求是否來自同一會話;日志中的接收日期為前一個請求的結束;請求時間為新請求的等待時間;keep-alive request time 存活請求時間為超時時間,綁定 "timeout http-keep-alive" 或 "timeout http-request"的設置。
這個操作可以設置在frontend或backend上,只要其上可以建立連接。需要注意的是,這個選項可以與 "option httpclose"結合, 但 "option httpclose"優先級更高,結合后基本實現了forceclose的效果。
option http-pretend-keepalive (http-假裝-長連接)
no option http-pretend-keepalive
Define whether haproxy will announce keepalive to the server or not 定義 haproxy 與服務器是否是 keepalive 的。
May be used in sections : defaults | frontend | listen | backend
yes | yes | yes | yes
Arguments : none
當聲明了 "option http-server-close" 或 "option forceclose", haproxy會在給server的request頭中添加 "Connection: close" 。然而有些服務器看到這個頭,會返回未知長度的response,並自動避免chunked encoding,其實這是不對的。它會阻止haproxy保持客戶端長連接,還會使客戶端或緩存接收了未完成的響應,卻認為響應結束了。
設置 "option http-pretend-keepalive", haproxy會在服務器端保持長連接,服務端則不會出現前面的問題。當 haproxy 獲取了完整的response, 才會以類似forceclose的方式關閉服務端。這樣客戶端得到一個普通的響應,連接也在服務端被正常關閉。
建議不將其設為默認值,因為大部分服務器會在發送完最后一個包之后更高效的關閉連接,並釋放緩存,而且網絡上的數據包也會略微降低整體的峰值性能。但是啟用該選項,haproxy會略微少做一些工作。所以如果haproxy在整個架構中是個瓶頸,可以啟用該操作,以節省CPU。
這個選項可以設置在frontend或backend上,只要其上可以建立連接。這個選項可以與 "option httpclose"結合, 使服務端keepalive,客戶端close,但並不建議這樣做。
balance <algorithm> [ <arguments> ]
balance url_param <param> [check_post [<max_wait>]]
定義選擇后端服務的負載均衡算法
May be used in sections : defaults | frontend | listen | backend
yes | no | yes | yes
Arguments :
<algorithm> 是負載均衡時選擇服務器的算法,沒有持續信息時可用,或連接重定向到另一個服務器。<algorithm> 可以是以下幾種:
roundrobin 每個服務器根據權重輪流使用,如果服務器的處理時間平均分布,這是最流暢和公平的算法。算法是動態的,對於實例啟動慢的服務器的權重會在運行中調整。每個backend的活動服務器在設計上限制為4128個。在一些大的群里面, 當服務器很短的宕機后恢復回來,有時會有幾百個請求被重新整合到群當中,並開始接收處理。盡管很少發生,但是很正常。這也說明了有機會監視它們,所以不必擔心。
static-rr 每個服務器根據權重輪流使用,類似roundrobin,但它是靜態的,意味着運行時修改權重是無效的。另一方面,它對服務器的數量沒有設計上的限制,服務器啟動后便會立即進到群中,整個分發方案會重新計算。這會略微降低CPU的運行(約1%)。
leastconn 連接數最低的服務器優先接收連接。Round-robin用於負載相同的服務器,使每台服務器都被使用。leastconn建議用於長會話服務,例如LDAP, SQL, TSE等,而不是很適合短會話協議,如HTTP。算法是動態的,對於實例啟動慢的服務器的權重會在運行中調整。
source 對源IP地址進行哈希,用可用服務器的權重總數除以哈希值,根據結果進行分配。只要服務器正常,同一個客戶端IP地址總是訪問同一台服務器。如果哈希的結果隨可用服務器數量而變化,那么有的客戶端會定向到不同的服務器。該算法一般用於不能插入cookie的TCP模式。它還可以用於廣域網上,為拒絕使用會話cookie的客戶端提供最有效的粘連。該算法默認是靜態的,所以運行時修改服務器的權重是無效的,但是算法會根據"hash-type"的變化做調整。
uri 對URI左端(問號之前)進行哈希,用可用服務器的權重總數除以哈希值,根據結果進行分配。只要服務器正常,同一個URI地址總是訪問同一台服務器。一般用於代理緩存和反病毒代理,以最大限度的提高緩存的命中率。該算法只能用於HTTP后端。該算法默認是靜態的,所以運行時修改服務器的權重是無效的,但是算法會根據"hash-type"的變化做調整。
算法支持兩個可選參數"len" 和 "depth", 都是后跟正整數。“len”參數指定算法只處理URI從頭開始的字符數,據此計算哈希。因為大多URI以"/"開頭,所以"len"最好不要設為1。"depth" 參數指定URI中最大的路徑深度,據此計算哈希。請求中的每個斜線為一級。如果同時聲明了這兩個參數,則截取URI時必須同時滿足。
url_param 在HTTP GET請求的查詢串中查找<param>中指定的URL參數。
若使用了修飾符"check_post",如果在URL問號('?')后面的查詢串中找不到參數,就會搜索HTTP POST 請求實體。或者在指定的一些字節后面嘗試搜索消息體。如果搜索不到實體, 則使用round robin算法。例如,假設客戶端總是在前128個字節發送LB參數,就可以指定它。默認為48。如果到達網關的字節數量不夠,實體數據是檢索不到的,至少有:(default/max_wait, Content-Length or first chunk length)。如果Content-Length沒有或為0,就不需要等待客戶端發送更多的數據。當Content-Length有值且大於<max_wait>,則等待僅限於<max_wait>,並假設有足夠的數據用於搜索參數的存在。萬一Transfer-Encoding被用了,則只能檢查第一個塊。如果參數值被塊邊界分隔開,則只能隨機均衡負載了。
如果參數后面跟着 ('=') 和一個值,則可以根據這個值進行哈希,用可用服務器的權重總數除以哈希值,根據結果進行分配。
還可用於跟蹤請求中的用戶身份,只要服務器正常,同一個用戶ID的請求總是發給同一台服務器。如果沒有參數或參數沒有值,則使用輪詢算法。該算法只用於HTTP后端。該算法默認是靜態的,所以運行時修改服務器的權重是無效的,但是算法會根據"hash-type"的變化做調整。
hdr(name) 在每個HTTP請求中查找HTTP頭<name>。與ACL函數'hdr()'一樣。括號括起來的頭名字不區分大小寫。如果缺少頭或頭沒有任何值,則使用roundrobin算法代替。
啟用參數'use_domain_only',哈希算法將只用於一些類似'Host'的特定頭的主域部分。例如主機值"haproxy.1wt.eu",則只考慮 "1wt"。該算法默認是靜態的,所以運行時修改服務器的權重是無效的,但是算法會根據"hash-type"的變化做調整。
rdp-cookie
rdp-cookie(name)
為每個進來的TCP請求查詢並哈希RDP cookie <name> (或“mstshash”如果省略) 。與ACL函數 'req_rdp_cookie()'一樣,name不區分大小寫。該機制用於退化的持久模式,可以使同一個用戶(或同一個會話ID)總是發送給同一台服務器。如果沒有cookie, 則使用roundrobin算法代替。
必須注意該聲明要生效,前端必須確保在請求緩沖中已經有RDP cookie,所以必須使用規則tcp-request content accept' 和ACL 'req_rdp_cookie_cnt'相結合。
該算法默認是靜態的,所以運行時修改服務器的權重是無效的,但是算法會根據"hash-type"的變化做調整。
<arguments> 是用於一些算法的可選參數列表,目前只有"url_param" 和 "uri" 用到,例如:
balance uri [len <len>] [depth <depth>]
balance url_param <param> [check_post [<max_wait>]]
如果沒有其他算法、模式或選項的設置,后端的負載均衡算法默認為roundrobin。每個后端只能設置一種。
Examples :
balance roundrobin
balance url_param userid
balance url_param session_id check_post 64
balance hdr(User-Agent)
balance hdr(host)
balance hdr(Host) use_domain_only
注意: 以下的警告和限制是使用“check_post“擴展和”url_param”所必須考慮 :
- 所有POST請求都要考慮,因為在包含二進制數據的體或實體中,沒有辦法決定是否會找到參數。因此需要另一種方法,限制POST請求的體中不含有URL參數 (見 acl reqideny http_end)
- 大於請求緩沖大小的 <max_wait> 值是沒用的。在build時設置緩沖大小,默認16KB。
- 不支持Content-Encoding, 參數搜索會失敗;負載均衡會改用 Round Robin。
- 預計: 不支持100-continue,負載均衡會改用 Round Robin。
- Transfer-Encoding (RFC2616 3.6.1) 只在第一個塊中支持。如果在第一個塊中的參數值不完整,選擇的服務器就沒有定義。(實際上取決於在第一個塊中定義的有多小)
- 該特性不支持生成100, 411 或 501 響應。
- 有的情況下,需要"check_post"只是要查看整個消息體的內容。檢查一般會停在任意數量的空格(LWS: linear
white space)或控制符上,表示這可能是一個URL參數列表。這可能不是一個關於SGML的類型消息體。
See also : "dispatch", "cookie", "appsession", "transparent", "hash-type" and "http_proxy".
hash-type <method>
將哈希映射到服務器的方法。Specify a method to use for mapping hashes to servers
May be used in sections : defaults | frontend | listen | backend
yes | no | yes | yes
Arguments :
map-based 哈希表是包含所有在線服務器的靜態數組。哈希結果很平滑,並考慮了權重,但是會忽略服務器啟動時的權重變化,也就是說不能慢啟動。另外,服務器是根據數組中的位置所選擇的,所以服務器數量變化時,大部分映射也會變化。當一台服務器啟動或關閉,或服務器加入到群中,大部分連接會再分配給不同的服務器,這對有緩存的實例會比較麻煩。
consistent 哈希表是由每個服務器構成的樹,會在樹上查找哈希Key,並選擇最近的服務器。這種哈希是動態的,支持服務器啟動時修改權重,所以可以慢啟動。它有一個好處是當服務器啟動或關閉時,只有其本身的關系被移除,當服務器加入群時,只有一小部分的映射會被重新分配,所以是一個比較理想的支持緩存的算法。但是根據其原理,算法不會非常平滑,有時候必須調整服務器的權重或ID來獲得更平衡的分布。要保持多次負載均衡時的相同分布,服務器ID是絕對不能變的。(roloand:haproxy根據服務器的ID初始化其哈希值)
默認值是"map-based",建議大部分情況下使用。
See also : "balance", "server"
dispatch <address>:<port>
設置一個默認的服務器地址
May be used in sections : defaults | frontend | listen | backend
no | no | yes | yes
Arguments : none
<address> 默認服務器的IPv4地址,也可以是主機名稱,名稱只在啟動時解析為IP地址。
<ports> 端口號,所有連接都會發送給這個端口,但是不允許像其他服務器一樣使用端口偏移(port offsets)。
"dispatch"關鍵字指定了一個默認的服務器,用於無可用服務器時的連接的處理。過去常用於前傳非持久連接給后備負載均衡器,由於定義簡單,還用於簡單的TCP中繼(TCP relays)。 建議對於明確的連接處理,應使用"server"直接聲明。
====================
一:Global parameters
* Process management and security
- chroot 改變當前工作目錄
- daemon 運行方式為后台工作
- user - group 工作用戶和組
-log <address> <facility>日志輸出設備
- nbproc 創建工作的進程數目
-pidfile pid文件位置
- ulimit-n 設置每個進程的可用的最大文件描述符
- stats 創建監控所用的套接字目錄
- node 創建另外一個節點名字共用一個IP地址,用來識別哪個節點在處理流量
- description 描述實例的名稱
maxconn <number> 每個進程可用的最大連接數
maxpipes <number> 每個進程可用的最大管道數
nokqueue nopoll nosepoll nosplice 禁用這些功能
spread-checks <0..50, in percent> health check 的時間間隔
tune.bufsize <number>
tune.maxaccept <number>
tune.maxpollevents <number>
tune.maxrewrite <number>
tune.rcvbuf.client <number>
tune.rcvbuf.server <number>
tune.sndbuf.client <number>
tune.sndbuf.server <number>
以上憑字面理解吧
debug 調試模式,輸出啟動信息到標准輸出
quiet 安裝模式,啟動時無輸出
二:defaults 塊
作用於其后緊跟的listen塊,直至下一個defaults 塊,下一個default 將替換上一個塊作用於以后的listen
frontend 塊,接受請求的端口組
backend塊,后端處理的server 組
listen塊,frontend和backend 塊的結合
三:常用配置命令
balance <algorithm> [ <arguments> ]
balance url_param <param> [check_post [<max_wait>]] 負載均衡模塊設置
Examples :
balance roundrobin
balance url_param userid
balance url_param session_id check_post 64
balance hdr(User-Agent)
balance hdr(host)
balance hdr(Host) use_domain_only
block { if | unless } <condition> 在7層阻止訪問
Example:
acl invalid_src src 0.0.0.0/7 224.0.0.0/3 acl定義和squid 很像
acl invalid_src src_port 0:1023
acl local_dst hdr(host) -i localhost
block if invalid_src || local_dst
capture cookie <name> len <length> 在請求和回應包中捕捉記錄指定長度的cookie,name 為cookie的開頭幾個字母
Example:
capture cookie ASPSESSION len 32
capture request header <name> len <length>
capture response header <name> len <length> 同上
clitimeout <timeout> (deprecated)
contimeout <timeout> (deprecated) 客戶端超時時間,不贊成設置
cookie <name> [ rewrite | insert | prefix ] [ indirect ] [ nocache ] [ postonly ] [ domain <domain> ]* 允許持續的基於cookie 的后端連接
default_backend <backend> 默認應用的后端
Example :
use_backend dynamic if url_dyn
use_backend static if url_css url_img extension_img
default_backend dynamic 當沒有匹配時就用dynamic
errorfile <code> <file> 定義出現錯誤的代碼的返回頁
Example :
errorfile 400 /etc/haproxy/errorfiles/400badreq.http
errorfile 403 /etc/haproxy/errorfiles/403forbid.http
errorfile 503 /etc/haproxy/errorfiles/503sorry.http
errorloc <code> <url> errorloc302 <code> <url> 出錯重定向到指定url
force-persist { if | unless } <condition> 在特定條件下,強制繼續連接down 掉的服務器后端
fullconn <conns> 定義后端組的最大連接數
grace <time> haproxy停止后,再持續多長時間用於處理連接
http-check disable-on-404 如果后端檢測返回404,將不再把后端計入負載均衡
http-check send-state 允許haproxy 發送 X-Haproxy-Server-State
http-request { allow | deny | http-auth [realm <realm>] } [ { if | unless } <condition> ] 七層訪問控制
Example:
acl nagios src 192.168.129.3
acl local_net src 192.168.0.0/16
acl auth_ok http_auth(L1)
http-request allow if nagios
http-request allow if local_net auth_ok
http-request auth realm Gimme if local_net auth_ok
http-request deny
Example:
acl auth_ok http_auth_group(L1) G1
http-request auth unless auth_ok
mode { tcp|http|health } 設定啟動的實例的協議類型
monitor fail { if | unless } <condition> 監控失敗條件設置
option abortonclose 丟棄由於客戶端等待時間過長而關閉連接但仍在haproxy等待隊列中的請求
option accept-invalid-http-request 接受無效的http請求,建議關閉(開啟可能有安全隱患)
option accept-invalid-http-response 接受無效的response ,建議關閉
option allbackups 應該是后備服務器,如果正常的后端無法使用,就使用這些后備的設備,balance方式還是用原來的,沒有優先的選擇,常用來提供錯誤的頁面
option checkcache 分析后端response,阻止可緩存的cookie,它對response 進行嚴格檢查,包括"Cache-control", "Pragma" and "Set-cookie" ,查看在客戶端代理那邊保存是否有風險,如果這個允許的話,符全以下條件 的response 將被允許,其它的將被阻止。
- all those without "Set-Cookie" header ;
- all those with a return code other than 200, 203, 206, 300, 301, 410,
provided that the server has not set a "Cache-control: public" header ;
- all those that come from a POST request, provided that the server has not
set a 'Cache-Control: public' header ;
- those with a 'Pragma: no-cache' header
- those with a 'Cache-control: private' header
- those with a 'Cache-control: no-store' header
- those with a 'Cache-control: max-age=0' header
- those with a 'Cache-control: s-maxage=0' header
- those with a 'Cache-control: no-cache' header
- those with a 'Cache-control: no-cache="set-cookie"' header
- those with a 'Cache-control: no-cache="set-cookie,' header
(allowing other fields after set-cookie)
option clitcpka 是否允許客戶端發送tcp keepalive 包,這個和http 的keepalive 沒有關系
option contstats 允許連續的流量統計更新
option dontlog-normal 開啟正常連接的日志
option dontlognull 記錄空連接
option forceclose 允許關閉session 在后端把response 發送后
option forwardfor [ except <network> ] [ header <name> ] 允許在request 中加入X-Forwarded-For header 發往server
option http-pretend-keepalive 定義是否haproxy要宣布同server keepalive
option http-server-close 是否開啟在server 端 connection closing
option http-use-proxy-header 用non-standard Proxy-Connection 替換 connection
option httpchk <method> <uri> <version> 允許用http協議檢查server 的健康
Examples :
# Relay HTTPS traffic to Apache instance and check service availability
# using HTTP request "OPTIONS * HTTP/1.1" on port 80.
backend https_relay
mode tcp
option httpchk OPTIONS * HTTP/1.1\r\nHost:\ www
server apache1 192.168.1.1:443 check port 80
option httplog [ clf ] 定制日志格式
option http_proxy 開啟http 代理模式,只有最基本的代理功能
option ignore-persist { if | unless } <condition> 在某條件下拒絕持續連接,適用於對靜態文件的負載均衡
option independant-streams 啟用雙向超時處理,如socket 的read 和write
option log-health-checks 記錄健康檢查日志
option log-separate-errors 對非完全成功的連接改變日志記錄等級
option logasap 大傳輸大文件時可以提前記錄日志
option mysql-check mysql 健康檢查
option nolinger 清除骯臟連接后開成的tcp 狀態及占用的資源,不過並不是強列要求你用這個選項,當然如果你有thousands of FIN_WAIT1 sessions on your system ,那肯定得用了
option originalto [ except <network> ] [ header <name> ] 允許在requests中加入X-Original-To header 發往server
option persist 強制將http請求發往已經down 掉的server
option redispatch 是否允許重新分配在session 失敗后
option smtpchk smtp 檢查
option socket-stats 允許對單個socket進行統計
option srvtcpka 是否允許向server 發送keepalive
option tcpka 是否允許向server和client發送keepalive
option tcplog 允許記錄tcp 連接的狀態和時間
option transparent 允許客戶端透明代理
rate-limit sessions <rate> 設置frontend 每秒處理的連接的上限,如果到達上限就停止建立新的connection
redirect location <to> [code <code>] <option> [{if | unless} <condition>]
redirect prefix <to> [code <code>] <option> [{if | unless} <condition>] 重定向,相當於rewrite
Example: move the login URL only to HTTPS.
acl clear dst_port 80
acl secure dst_port 8080
acl login_page url_beg /login
acl logout url_beg /logout
acl uid_given url_reg /login?userid=[^&]+
acl cookie_set hdr_sub(cookie) SEEN=1
redirect prefix https://mysite.com set-cookie SEEN=1 if !cookie_set
redirect prefix https://mysite.com if login_page !secure
redirect prefix http://mysite.com drop-query if login_page !uid_given
redirect location http://mysite.com/ if !login_page secure
redirect location / clear-cookie USERID= if logout
Example: send redirects for request for articles without a '/'.
acl missing_slash path_reg ^/article/[^/]*$
redirect code 301 prefix / drop-query append-slash if missing_slash
redisp (deprecated)
redispatch (deprecated) 開啟session 重新分配在connection連接失敗后,不贊成啟用
reqadd <string> [{if | unless} <cond>] 在http請示的末尾加上string
Example : add "X-Proto: SSL" to requests coming via port 81
acl is-ssl dst_port 81
reqadd X-Proto:\ SSL if is-ssl
reqallow <search> [{if | unless} <cond>]
reqiallow <search> [{if | unless} <cond>] (ignore case) request 請求訪問控制
Example :
# allow www.* but refuse *.local
reqiallow ^Host:\ www\.
reqideny ^Host:\ .*\.local
reqdel <search> [{if | unless} <cond>]
reqidel <search> [{if | unless} <cond>] (ignore case) 刪除請求的head 中的內容
Example :
# remove X-Forwarded-For header and SERVER cookie
reqidel ^X-Forwarded-For:.*
reqidel ^Cookie:.*SERVER=
reqdeny <search> [{if | unless} <cond>]
reqideny <search> [{if | unless} <cond>] (ignore case) 拒絕訪問
reqrep <search> <string> [{if | unless} <cond>]
reqirep <search> <string> [{if | unless} <cond>] (ignore case) request 請求替換
Example :
# replace "/static/" with "/" at the beginning of any request path.
reqrep ^([^\ ]*)\ /static/(.*) \1\ /\2
# replace "www.mydomain.com" with "www" in the host name.
reqirep ^Host:\ www.mydomain.com Host:\ www
reqtarpit <search> [{if | unless} <cond>]
reqitarpit <search> [{if | unless} <cond>] (ignore case) 阻止http請求中的某些信息
Examples :
# ignore user-agents reporting any flavour of "Mozilla" or "MSIE", but
# block all others.
reqipass ^User-Agent:\.*(Mozilla|MSIE)
reqitarpit ^User-Agent:
# block bad guys
acl badguys src 10.1.0.3 172.16.13.20/28
reqitarpit . if badguys
retries <value> 當對server的connection失敗后,重試的次數
rspadd <string> [{if | unless} <cond>] response 增加信息
rspdel <search> [{if | unless} <cond>]
rspidel <search> [{if | unless} <cond>] (ignore case)
rspdeny <search> [{if | unless} <cond>]
rspideny <search> [{if | unless} <cond>] (ignore case)
rsprep <search> <string> [{if | unless} <cond>]
rspirep <search> <string> [{if | unless} <cond>] (ignore case)
以上和request 的差不多
source <addr>[:<port>] [usesrc { <addr2>[:<port2>] | client | clientip } ] 定義從代理出去的連接的對象,用於限定地址可以訪問server
一些timeout
srvtimeout <timeout> server 處理超時,不贊成設置
timeout check X - X X
timeout client X X X -
timeout clitimeout (deprecated) X X X -
timeout connect X - X X
timeout contimeout (deprecated) X - X X
timeout http-keep-alive X X X X
timeout http-request X X X X
timeout queue X - X X
timeout server X - X X
timeout srvtimeout (deprecated) X - X X
timeout tarpit X X X X
stats auth <user>:<passwd> 監控統計的帳號和密碼
backend public_www
server srv1 192.168.0.1:80
stats enable
stats hide-version
stats scope .
stats uri /admin?stats
stats realm Haproxy\ Statistics
stats auth admin1:AdMiN123
stats auth admin2:AdMiN321
# internal monitoring access (unlimited)
backend private_monitoring
stats enable
stats uri /admin?stats
stats refresh 5s
還有很多參數,以上能用到的也沒有幾個,只要滿足當前需求就好,對於性能要求高的話,建議把不需要的功能 都關了吧.
====================
HAProxy的配置示例
HAProxy配置中分成五部分內容,當然這些組件不是必選的,可以根據需要選擇部分作為配置。
global:參數是進程級的,通常和操作系統(OS)相關。這些參數一般只設置一次,如果配置無誤,就不需要再次配置進行修改
defaults:配置默認參數的,這些參數可以被利用配置到frontend,backend,listen組件
frontend:接收請求的前端虛擬節點,Frontend可以根據規則直接指定具體使用后端的 backend(可動態選擇)。
backend:后端服務集群的配置,是真實的服務器,一個Backend對應一個或者多個實體服務器。
listen:Frontend和Backend的組合體。
下面是HAProxy的一些常用的配置,這個配置是用來說明HAProxy的一些常用功能的配置,具體詳細配置請查看安裝目錄下的doc目錄下的文檔文件,或者到http://cn.haproxy.org/下載中文配置說明文檔
配置具體實例,后附說明:
global
#全局的日志配置 其中日志級別是[err warning info debug]
#local0 是日志設備,必須為如下24種標准syslog設備的一種:
#kern user mail daemon auth syslog lpr news
#uucp cron auth2 ftp ntp audit alert cron2
#local0 local1 local2 local3 local4 local5 local6 local7
#但是之前在/etc/syslog.conf文件中定義的是local0所以
#這里也是用local0
log 127.0.0.1 local0 info #[err warning info debug]
#最大連接數
maxconn 4096
#用戶
user admin
#組
group admin
#使HAProxy進程進入后台運行。這是推薦的運行模式
daemon
#創建4個進程進入deamon模式運行。此參數要求將運行模式設置為"daemon"
nbproc 4
#將所有進程的pid寫入文件 啟動進程的用戶必須有權限訪問此文件。
pidfile /home/admin/haproxy/logs/haproxy.pid
defaults
#默認的模式mode { tcp|http|health },tcp是4層,http是7層,health只會返回OK
mode http
#采用http日志格式
option httplog
#三次連接失敗就認為是服務器不可用,也可以通過后面設置
retries 3
如果cookie寫入了serverId而客戶端不會刷新cookie,
#當serverId對應的服務器掛掉后,強制定向到其他健康的服務器
option redispatch
#當服務器負載很高的時候,自動結束掉當前隊列處理比較久的鏈接
option abortonclose
#默認的最大連接數
maxconn 4096
#連接超時
contimeout 5000
#客戶端超時
clitimeout 30000
#服務器超時
srvtimeout 30000
#=心跳檢測超時
timeout check 2000
#注:一些參數值為時間,比如說timeout。時間值通常單位為毫秒(ms),但是也可以通過加#后綴,來使用其他的單位。
#- us : microseconds. 1 microsecond = 1/1000000 second
#- ms : milliseconds. 1 millisecond = 1/1000 second. This is the default.
#- s : seconds. 1s = 1000ms
#- m : minutes. 1m = 60s = 60000ms
#- h : hours. 1h = 60m = 3600s = 3600000ms
#- d : days. 1d = 24h = 1440m = 86400s = 86400000ms
########統計頁面配置############
listen admin_stats
#監聽端口
bind 0.0.0.0:1080
#http的7層模式
mode http
#日志設置
log 127.0.0.1 local0 err #[err warning info debug]
#統計頁面自動刷新時間
stats refresh 30s
#統計頁面url
stats uri /admin?stats
#統計頁面密碼框上提示文本
stats realm Gemini\ Haproxy
#統計頁面用戶名和密碼設置
stats auth admin:admin
stats auth admin1:admin1
#隱藏統計頁面上HAProxy的版本信息
stats hide-version
#######網站檢測listen定義############
listen site_status
bind 0.0.0.0:1081
mode http
log 127.0.0.1 local0 err #[err warning info debug]
#網站健康檢測URL,用來檢測HAProxy管理的網站是否可以用,正常返回200,不正常返回500
monitor-uri /site_status
#定義網站down時的策略
#當掛在負載均衡上的指定backend的中有效機器數小於1台時返回true
acl site_dead nbsrv(denali_server) lt 1
acl site_dead nbsrv(tm_server) lt 1
acl site_dead nbsrv(mms_server) lt 1
#當滿足策略的時候返回500
monitor fail if site_dead
#如果192.168.0.252或者192.168.0.31這兩天機器掛了
#認為網站掛了,這時候返回500,判斷標准是如果mode是
#http返回200認為是正常的,如果mode是tcp認為端口暢通是好的
monitor-net 192.168.0.252/31
########frontend配置############
frontend http_80_in
#監聽端口
bind 0.0.0.0:80
#http的7層模式
mode http
#應用全局的日志配置
log global
#啟用http的log
option httplog
#每次請求完畢后主動關閉http通道,HA-Proxy不支持keep-alive模式
option httpclose
#如果后端服務器需要獲得客戶端的真實IP需要配置次參數,將可以從Http Header中
#獲得客戶端IP
option forwardfor
###########HAProxy的日志記錄內容配置##########
capture request header Host len 40
capture request header Content-Length len 10
capture request header Referer len 200
capture response header Server len 40
capture response header Content-Length len 10
capture response header Cache-Control len 8
####################acl策略定義#########################
#如果請求的域名滿足正則表達式返回true -i是忽略大小寫
acl denali_policy hdr_reg(host) -i ^(www.gemini.taobao.net|my.gemini.taobao.net|auction1.gemini.taobao.net)$
#如果請求域名滿足trade.gemini.taobao.net 返回 true -i是忽略大小寫
acl tm_policy hdr_dom(host) -i trade.gemini.taobao.net
##在請求url中包含sip_apiname=,則此控制策略返回true,否則為false
acl invalid_req url_sub -i sip_apiname=
##在請求url中存在timetask作為部分地址路徑,則此控制策略返回true,否則返回false
acl timetask_req url_dir -i timetask
#當請求的header中Content-length等於0時返回 true
acl missing_cl hdr_cnt(Content-length) eq 0
######################acl策略匹配相應###################
##當請求中header中Content-length等於0 阻止請求返回403
block if missing_cl
##block表示阻止請求,返回403錯誤,當前表示如果不滿足策略invalid_req,或者滿足策略timetask_req,則阻止請求。
block if !invalid_req || timetask_req
#當滿足denali_policy的策略時使用denali_server的backend
use_backend denali_server if denali_policy
#當滿足tm_policy的策略時使用tm_server的backend
use_backend tm_server if tm_policy
#reqisetbe關鍵字定義,根據定義的關鍵字選擇backend
reqisetbe ^Host:\ img dynamic
reqisetbe ^[^\ ]*\ /(img|css)/ dynamic
reqisetbe ^[^\ ]*\ /admin/stats stats
#以上都不滿足的時候使用默認mms_server的backend
default_backend mms_server
#HAProxy錯誤頁面設置
errorfile 400 /home/admin/haproxy/errorfiles/400.http
errorfile 403 /home/admin/haproxy/errorfiles/403.http
errorfile 408 /home/admin/haproxy/errorfiles/408.http
errorfile 500 /home/admin/haproxy/errorfiles/500.http
errorfile 502 /home/admin/haproxy/errorfiles/502.http
errorfile 503 /home/admin/haproxy/errorfiles/503.http
errorfile 504 /home/admin/haproxy/errorfiles/504.http
##########backend的設置##############
backend mms_server
#http的7層模式
mode http
#負載均衡的方式,roundrobin平均方式
balance roundrobin
#允許插入serverid到cookie中,serverid后面可以定義
cookie SERVERID
#心跳檢測的URL,HTTP/1.1¥r¥nHost:XXXX,指定了心跳檢測HTTP的版本,XXX為檢測時請求
#服務器的request中的域名是什么,這個在應用的檢測URL對應的功能有對域名依賴的話需要設置
option httpchk GET /member/login.jhtml HTTP/1.1\r\nHost:member1.gemini.taobao.net
#服務器定義,cookie 1表示serverid為1,check inter 1500 是檢測心跳頻率
#rise 3是3次正確認為服務器可用,fall 3是3次失敗認為服務器不可用,weight代表權重
server mms1 10.1.5.134:80 cookie 1 check inter 1500 rise 3 fall 3 weight 1
server mms2 10.1.6.118:80 cookie 2 check inter 1500 rise 3 fall 3 weight 2
backend denali_server
mode http
#負載均衡的方式,source根據客戶端IP進行哈希的方式
balance source
#但設置了backup的時候,默認第一個backup會優先,設置option allbackups后
#所有備份服務器權重一樣
option allbackups
#心跳檢測URL設置
option httpchk GET /mytaobao/home/my_taobao.jhtml HTTP/1.1\r\nHost:my.gemini.taobao.net
#可以根據機器的性能不同,不使用默認的連接數配置而使用自己的特殊的連接數配置
#如minconn 10 maxconn 20
server denlai1 10.1.5.114:80 minconn 4 maxconn 12 check inter 1500 rise 3 fall 3
server denlai2 10.1.6.104:80 minconn 10 maxconn 20 check inter 1500 rise 3 fall 3
#備份機器配置,正常情況下備機不會使用,當主機的全部服務器都down的時候備備機會啟用
server dnali-back1 10.1.7.114:80 check backup inter 1500 rise 3 fall 3
server dnali-back2 10.1.7.114:80 check backup inter 1500 rise 3 fall 3
backend tm_server
mode http
#負載均衡的方式,leastconn根據服務器當前的請求數,取當前請求數最少的服務器
balance leastconn
option httpchk GET /trade/itemlist/prepayCard.htm HTTP/1.1\r\nHost:trade.gemini.taobao.ne
server tm1 10.1.5.115:80 check inter 1500 rise 3 fall 3
server tm2 10.1.6.105:80 check inter 1500 rise 3 fall 3
######reqisetbe自定義關鍵字匹配backend部分#######################
backend dynamic
mode http
balance source
option httpchk GET /welcome.html HTTP/1.1\r\nHost:www.taobao.net
server denlai1 10.3.5.114:80 check inter 1500 rise 3 fall 3
server denlai2 10.4.6.104:80 check inter 1500 rise 3 fall 3
backend stats
mode http
balance source
option httpchk GET /welcome.html HTTP/1.1\r\n Host:www.163.com
server denlai1 10.5.5.114:80 check inter 1500 rise 3 fall 3
server denlai2 10.6.6.104:80 check inter 1500 rise 3 fall 3