Haproxy 配置项\配置实例

经常使用配置选项:css

 

OPTION 选项:html

option httpclose :HAProxy会针对客户端的第一条请求的返回添加cookie并返回给客户端,客户端发送后续请求时会发送前端

                             此cookie到HAProxy,HAProxy会针对此cookie分发到上次处理此请求的服务器上,若是服务器不能忽略node

                             此cookie值会影响处理结果。若是避免这种状况配置此选项,防止产生多余的cookie信息。mysql

option forwardfor :若是服务器上的应用程序想记录发起请求的客户端的IP地址,须要在HAProxy上配置此选项,这样ios

                               HAProxy会把客户端的IP信息发送给服务器,在HTTP请求中添加"X-Forwarded-For"字段。正则表达式

option originalto :若是服务器上的应用程序想记录发起请求的原目的IP地址,须要在HAProxy上配置此选项,这样HAProxyredis

                              会添加"X-Original-To"字段。算法

option dontlognull :保证HAProxy不记录上级负载均衡发送过来的用于检测状态没有数据的心跳包。sql

 

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

相关文章
相关标签/搜索