--- title: "4. 代理" linkTitle: "4. 代理" weight: 150 description: "默认设置、前端、后端、监听器、代理关键字及动作引用" icon: fa-solid fa-right-left module: [HAPROXY] categories: [参考] aliases: - /haproxy/configuration/proxies/ - /docs/haproxy/configuration/proxies/ - /haproxy/proxies/ upstream_link: "https://docs.haproxy.org/3.4/configuration.html" upstream_name: "HAProxy 3.4 Configuration Manual" upstream_ref: "v3.4.4, chapter 4" --- 代理配置可位于一组段中: - defaults [``] [ from `` ] - frontend `` [ from `` ] - backend `` [ from `` ] - listen `` [ from `` ] 前端段描述了一组用于接收客户端连接的监听套接字。 后端段描述了一组代理将连接以转发传入连接的服务器。 段 "listen" 定义了一个完整的代理,其前端和后端部分合并于同一段中。该配置通常适用于仅 TCP 流量的场景。 默认设置段 “defaults” 段将所有设置重置为文档中定义的默认值,并为后续段落预设新的默认值。所有“frontend”、“backend”和“listen”段始终从一个“defaults”段获取初始设置,默认情况下使用在新创建段之前出现的最新一个“defaults”段。可以通过在段行中使用可选关键字“from”后指定名称,显式指定某个特定的“defaults”段作为初始设置来源。尽管“defaults”段不强制命名,但建议命名以提高可读性。这也是唯一一种指定使用特定段而非默认前一个段的方式。由于“defaults”段名称为可选,因此默认对名称采用非常宽松的校验,甚至允许名称重叠。然而,若某个“defaults”段被其他段引用,则其名称必须符合所有代理名称的语法要求,且在所有“defaults”段中必须唯一。请注意,尽管当前允许重复段名称,但建议一般情况下避免重复,并遵循与代理名称相同的命名语法。此规则未来版本中可能被强制执行。此外,若某个“defaults”段被某个代理显式引用,同时又因是最后一个定义的段而被另一个代理隐式引用,将发出警告。强烈建议避免混合使用显式引用和隐式引用,应始终使用显式引用,或添加一个专用于所有隐式引用的最后通用“defaults”段。 请注意,defaults 段甚至可以从另一个 defaults 段获取初始设置,从而跨多个层级的 defaults 段继承设置。这种方式可以方便地建立特定的配置模板,以承载一组默认设置(例如 TCP 与 HTTP 或短超时与长超时),但可能很快变得难以追踪。 默认情况下,命名的 defaults 段会在配置解析后保留,以便创建动态后端时复用。可通过全局关键字 `tune.defaults.purge` 改变此行为。 所有代理名称必须由大写字母、小写字母、数字、"-"(连字符)、'\_'(下划线)、'.'(点号)和 ":"(冒号)组成。ACL 名称区分大小写,这意味着 "www" 和 "WWW" 是两个不同的代理。 历史上,当满足某些条件时(例如,当代理不具备相同的前端/后端能力时),所有代理名称之间可以重叠,但这曾导致日志中出现过多问题,以及在 CLI 操作、stick-table 名称和统计信息检索方面造成混淆。现在,无论代理的具体能力如何,两个代理的名称必须不同。 目前,HAProxy 支持两种主要代理模式:“tcp”(也称为第 4 层)和 “http”(也称为第 7 层)。在第 4 层模式下,HAProxy 仅在两端之间转发双向流量。在第 7 层模式下,HAProxy 会分析协议,并可根据任意条件,对请求或响应中的任意内容执行允许、阻止、切换、添加、修改或移除操作。 在 HTTP 模式下,通过连接传输的请求和响应所应用的处理方式,取决于前端的 HTTP 选项与后端选项的组合。HAProxy 支持三种连接模式: - KAL:持久连接("option http-keep-alive")为默认模式:所有请求和响应均被处理,连接在响应与新请求之间保持打开状态但处于空闲状态。 - SCL:服务端关闭("option http-server-close"):在收到响应结束后,关闭面向服务器的连接,但保持面向客户端的连接打开。 - CLO:关闭(“option httpclose”):在响应结束之后关闭连接,并在两个方向上附加 "Connection: close"。 通过前端和后端的连接所采用的有效模式,可根据两个代理模式按以下矩阵确定,但简而言之,模式具有对称性,持久连接为最弱选项,关闭为最强选项。 Backend mode ```text | KAL | SCL | CLO ----+-----+-----+---- KAL | KAL | SCL | CLO ----+-----+-----+---- mode SCL | SCL | SCL | CLO ----+-----+-----+---- CLO | CLO | CLO | CLO ``` 可以将 TCP 前端与 HTTP 后端串联使用。若仅处理 HTTP 流量,则此举毫无意义。但可用于在同一个前端中处理多种协议。在此情况下,客户端连接首先作为原始 TCP 连接处理,随后升级为 HTTP。升级前,内容处理基于原始数据进行。升级后,数据将使用一种称为 HTX 的内部表示形式进行解析和存储,此时不再可能依赖原始表示形式。无法回退。 有两种升级方式:就地升级和破坏性升级。第一种涉及从 TCP 升级至 HTTP/1。在 HTTP/1 中,请求处理是串行的,因此应用层流可以被保留。第二种涉及从 TCP 升级至 HTTP/2。由于 HTTP/2 是多路复用协议,应用层流无法与任何 HTTP/2 流关联,因而被破坏。当 HAProxy 在底层 H2 多路复用器中接收到新的 HTTP/2 流时,会创建新的应用层流。理解这一差异至关重要,因为它会显著改变数据处理方式。执行 HTTP/1 升级时,对原始数据已执行的应用层处理既不会丢失也不会重新执行;而执行 HTTP/2 升级时,应用层流彼此独立,每个流都会系统性地重新评估所有前端规则。如前所述,第一个流(即 TCP 流)会被破坏,但仅在前端规则评估完成后。 当在 TCP 代理中执行 HTTP 处理时,还有一个重要点需要理解。 虽然 HAProxy 能够在 tcp-request 内容规则中实时解析 HTTP/1,但无法解析 HTTP/2。 仅能解析 HTTP/2 的前导信息(preface)。这在 TCP 环境下的 HTTP 内容分析中是一个重大限制。 具体而言,仅能判断接收到的数据是否为 HTTP。例如,无法根据 Host 头的值选择后端,而这一操作在 HTTP/1 中极为简单。 值得庆幸的是,存在一种解决方案可缓解此缺陷。 有两种方式执行 HTTP 升级。第一种是传统方法,即选择一个 HTTP 后端。当后端被设置时,升级即发生。因此,在就地升级场景下,仅考虑后端配置对 HTTP 数据处理的影响。在破坏性升级场景下,应用流被销毁,其处理过程也随之停止。采用此方法时,选择支持 HTTP/2 连接的后端的可能性极为有限,如上所述,且基本无实际意义,因为流已被销毁。第二种方法是在 tcp-request content 规则评估期间,通过 "switch-mode http" 动作执行升级。在此情况下,升级在前端上下文中进行,可以在该前端中定义 HTTP 指令。对于就地升级,可尽早获得 HTTP 分析的全部功能。其行为与 HTTP 前端非常接近。对于破坏性升级,除无法基于有限信息选择后端外,其余无实质影响。此方法为推荐方案。因此,仅需在 tcp-request content 规则中检测请求协议以执行 HTTP 升级即可。其余所有 HTTP 操作可移至前端 http-request 规则集。请注意,tcp-request content 规则始终在每个流上评估,此行为不可更改。 ## 4.1. 代理关键字矩阵 {#section-4-1} 以下关键词列表受支持。大多数关键词仅可在有限的段类型中使用。部分关键词标有“已弃用”,因其继承自旧语法,可能造成混淆或功能受限,现已推荐使用新关键词替代。标有“(\*)”的关键词可选择性地通过“no”前缀进行反转,例如“no option contstats”。当某选项默认已启用,而需在特定实例中禁用时,此用法有意义。此类选项还可使用“default”前缀,以恢复默认设置,无论此前“defaults”段中如何配置。标有“(!)”的关键词仅在命名的“defaults”段中受支持,不适用于匿名段。 请注意:部分危险且不推荐使用的指令故意未列在下表中。此举出于刻意。这些指令已有文档说明,但不在下方列出,也是为了进一步劝阻用户使用。 ```text keyword defaults frontend listen backend ------------------------------------+----------+----------+---------+--------- acl X (!) X X X backlog X X X - balance X - X X be-unpublished - - X X bind - X X - capture cookie - X X - capture request header - X X - capture response header - X X - clitcpka-cnt X X X - clitcpka-idle X X X - clitcpka-intvl X X X - compression X X X X cookie X - X X crt - X X - declare capture - X X - default-server X - X X default_backend X X X - description - X X X disabled X X X X dispatch (deprecated) - - X X email-alert from X X X X email-alert level X X X X email-alert mailers X X X X email-alert myhostname X X X X email-alert to X X X X enabled X X X X errorfile X X X X errorfiles X X X X errorloc X X X X errorloc302 X X X X -- keyword -------------------------- defaults - frontend - listen -- backend - errorloc303 X X X X error-log-format X X X - external-check command X - X X external-check path X - X X force-persist - - X X force-be-switch - X X - filter - X X X filter-sequence - X X X fullconn X - X X guid - X X X hash-balance-factor X - X X hash-preserve-affinity X - X X hash-type X - X X http-after-response X (!) X X X http-check comment X - X X http-check connect X - X X http-check disable-on-404 X - X X http-check expect X - X X http-check send X - X X http-check send-state X - X X http-check set-var X - X X http-check unset-var X - X X http-error X X X X http-request X (!) X X X http-response X (!) X X X http-reuse X - X X http-send-name-header X - X X id - X X X ignore-persist - - X X load-server-state-from-file X - X X log (*) X X X X log-format X X X - log-format-sd X X X - log-tag X X X X log-steps X X X - max-keep-alive-queue X - X X max-session-srv-conns X X X - maxconn X X X - mode X X X X monitor fail - X X - monitor-uri X X X - option abortonclose (*) X X X X option allbackups (*) X - X X option checkcache (*) X - X X option clitcpka (*) X X X - option contstats (*) X X X - option disable-h2-upgrade (*) X X X - option dontlog-normal (*) X X X - option dontlognull (*) X X X - -- keyword -------------------------- defaults - frontend - listen -- backend - option external-check X - X X option forwardfor X X X X option forwarded (*) X - X X option h1-case-adjust-bogus-client (*) X X X - option h1-case-adjust-bogus-server (*) X - X X option http-buffer-request (*) X X X X option http-drop-request-trailers (*) X - - X option http-drop-response-trailers (*) X - X - option http-ignore-probes (*) X X X - option http-keep-alive (*) X X X X option http-no-delay (*) X X X X option http-pretend-keepalive (*) X - X X option http-restrict-req-hdr-names X X X X option http-server-close (*) X X X X option http-use-proxy-header (*) X X X - option httpchk X - X X option httpclose (*) X X X X option httplog X X X - option httpslog X X X - option idle-close-on-response (*) X X X - option independent-streams (*) X X X X option ldap-check X - X X option log-health-checks (*) X - X X option log-separate-errors (*) X X X - option logasap (*) X X X - option mysql-check X - X X option nolinger (*) X X X X option originalto X X X X option persist (*) X - X X option pgsql-check X - X X option prefer-last-server (*) X - X X option redispatch (*) X - X X option redis-check X - X X option smtpchk X - X X option socket-stats (*) X X X - option splice-auto (*) X X X X option splice-request (*) X X X X option splice-response (*) X X X X option spop-check X - X X option srvtcpka (*) X - X X option ssl-hello-chk X - X X -- keyword -------------------------- defaults - frontend - listen -- backend - option tcp-check X - X X option tcp-smart-accept (*) X X X - option tcp-smart-connect (*) X - X X option tcpka X X X X option tcplog X X X - option transparent (deprecated) (*) X - X X option use-small-buffers (*) X - X X persist rdp-cookie X - X X quic-initial X (!) X X - rate-limit sessions X X X - redirect - X X X -- keyword -------------------------- defaults - frontend - listen -- backend - retries X - X X retry-on X - X X server - - X X server-state-file-name X - X X server-template - - X X source X - X X srvtcpka-cnt X - X X srvtcpka-idle X - X X srvtcpka-intvl X - X X stats admin - X X X stats auth X X X X stats enable X X X X stats hide-version X X X X stats http-request - X X X stats realm X X X X stats refresh X X X X stats scope X X X X stats show-desc X X X X stats show-legends X X X X stats show-node X X X X stats show-version X X X X stats uri X X X X -- keyword -------------------------- defaults - frontend - listen -- backend - stick match - - X X stick on - - X X stick store-request - - X X stick store-response - - X X stick-table - X X X tcp-check comment X - X X tcp-check connect X - X X tcp-check expect X - X X tcp-check send X - X X tcp-check send-lf X - X X tcp-check send-binary X - X X tcp-check send-binary-lf X - X X tcp-check set-var X - X X tcp-check unset-var X - X X tcp-request connection X (!) X X - tcp-request content X (!) X X X tcp-request inspect-delay X (!) X X X tcp-request session X (!) X X - tcp-response content X (!) - X X tcp-response inspect-delay X (!) - X X timeout check X - X X timeout client X X X - timeout client-fin X X X - timeout client-hs X X X - timeout connect 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 server-fin X - X X timeout tarpit X X X X timeout tunnel X - X X transparent (deprecated) X - X X unique-id-format X X X X unique-id-header X X X - use_backend - X X - use-fcgi-app - - X X use-server - - X X ------------------------------------+----------+----------+---------+--------- keyword defaults frontend listen backend ``` ## 4.2. 按字母顺序排序的关键字参考 {#section-4-2} 本段描述了每个关键字及其用法。 **`acl [flags] [operator] ...`** ```haproxy acl [flags] [operator] ... ``` 声明或完成访问控制列表。 可用于以下上下文:tcp、http 可出现在以下段中:defaults \| frontend \| listen \| backend yes(!) \| yes \| yes \| yes 该指令仅可在命名的 defaults 段中使用,不可在匿名段中使用。在 defaults 段中定义的 ACL 不可被使用该段的其他段访问。 示例: ```text acl invalid_src src 0.0.0.0/7 224.0.0.0/3 acl invalid_src src_port 0:1023 acl local_dst hdr(host) -i localhost ``` 请参阅 [第 7 节](/zh/docs/haproxy/acls-and-samples/) 了解 ACL 的使用方法。 **`backlog `** ```haproxy backlog ``` 向系统提供关于期望监听队列大小的近似提示 可用于以下上下文:tcp、http 可出现在以下段中:defaults \| frontend \| listen \| backend yes \| yes \| yes \| no 参数: ```text is the number of pending connections. Depending on the operating system, it may represent the number of already acknowledged connections, of non-acknowledged ones, or both. ``` 此选项仅对流监听器(包括 QUIC 监听器)有意义。然而,其行为与 QUIC 实例并不完全相同。 对于除 QUIC 以外的所有监听器,为防范 SYN 洪水攻击,一种解决方案是增大系统的 SYN 队列长度。根据系统不同,该参数有时可通过系统参数调整,有时则完全不可调,有时系统会依赖应用程序在调用 listen() 系统调用时提供的提示。默认情况下,HAProxy 会将前端的 maxconn 值传递给 listen() 系统调用。在能够利用该值的系统上,有时指定不同的值会更有用,因此引入了 backlog 参数。 在 Linux 2.4 上,该参数会被系统忽略。在 Linux 2.6 上,它作为提示使用,系统最多接受小于等于最小大于该值的 2 的幂次,且永远不会超过某些限制(通常为 32768)。 对于 QUIC 监听器,backlog 为活跃握手的最大数量和待接受连接的数量设定了共享上限。握手阶段主要依赖于与远端对等节点的网络延迟,而第二阶段则完全取决于 HAProxy 的负载。当任一限制达到时,HAProxy 将开始丢弃 INITIAL 数据包的接收,阻止任何新连接的分配,直至连接数量超出部分开始下降。此情况可能导致浏览器静默降级 HTTP 版本并切换至 TCP。 另请参阅:“maxconn”以及目标操作系统的调优指南。 **`balance [ ]`** ```haproxy balance [ ] balance url_param [check_post] ``` 定义后端所使用的负载均衡算法。 可用于以下上下文:tcp、http、log 可出现在以下段中:defaults \| frontend \| listen \| backend yes \| no \| yes \| yes 参数: ```text is the algorithm used to select a server when doing load balancing. This only applies when no persistence information is available, or when a connection is redispatched to another server. may be one of the following: roundrobin Each server is used in turns, according to their weights. This is the smoothest and fairest algorithm when the server's processing time remains equally distributed. This algorithm is dynamic, which means that server weights may be adjusted on the fly for slow starts for instance. It is limited by design to 4095 active servers per backend. Note that in some large farms, when a server becomes up after having been down for a very short time, it may sometimes take a few hundreds requests for it to be re-integrated into the farm and start receiving traffic. This is normal, though very rare. It is indicated here in case you would have the chance to observe it, so that you don't worry. Note: weights are ignored for backends in LOG mode. static-rr Each server is used in turns, according to their weights. This algorithm is as similar to roundrobin except that it is static, which means that changing a server's weight on the fly will have no effect. On the other hand, it has no design limitation on the number of servers, and when a server goes up, it is always immediately reintroduced into the farm, once the full map is recomputed. It also uses slightly less CPU to run (around -1%). This algorithm is not usable in LOG mode. leastconn The server with the lowest number of connections receives the connection. Round-robin is performed within groups of servers of the same load to ensure that all servers will be used. Use of this algorithm is recommended where very long sessions are expected, such as LDAP, SQL, TSE, etc... but is not very well suited for protocols using short sessions such as HTTP. This algorithm is dynamic, which means that server weights may be adjusted on the fly for slow starts for instance. It will also consider the number of queued connections in addition to the established ones in order to minimize queuing. This algorithm is not usable in LOG mode. first The first server with available connection slots receives the connection. The servers are chosen from the lowest numeric identifier to the highest (see server parameter "id"), which defaults to the server's position in the farm. Once a server reaches its maxconn value, the next server is used. It does not make sense to use this algorithm without setting maxconn. The purpose of this algorithm is to always use the smallest number of servers so that extra servers can be powered off during non-intensive hours. This algorithm ignores the server weight, and brings more benefit to long session such as RDP or IMAP than HTTP, though it can be useful there too. In order to use this algorithm efficiently, it is recommended that a cloud controller regularly checks server usage to turn them off when unused, and regularly checks backend queue to turn new servers on when the queue inflates. Alternatively, using "http-check send-state" may inform servers on the load. This algorithm is not usable in LOG mode. hash Takes a regular sample expression in argument. The expression is evaluated for each request and hashed according to the configured hash-type. The result of the hash is divided by the total weight of the running servers to designate which server will receive the request. This can be used in place of "source", "uri", "hdr()", "url_param()", "rdp-cookie" to make use of a converter, refine the evaluation, or be used to extract data from local variables for example. When the data is not available, round robin will apply. This algorithm is static by default, which means that changing a server's weight on the fly will have no effect, but this can be changed using "hash-type". This algorithm is not usable for backends in LOG mode, please use "log-hash" instead. source The source IP address is hashed and divided by the total weight of the running servers to designate which server will receive the request. This ensures that the same client IP address will always reach the same server as long as no server goes down or up. If the hash result changes due to the number of running servers changing, many clients will be directed to a different server. This algorithm is generally used in TCP mode where no cookie may be inserted. It may also be used on the Internet to provide a best-effort stickiness to clients which refuse session cookies. This algorithm is static by default, which means that changing a server's weight on the fly will have no effect, but this can be changed using "hash-type". See also the "hash" option above. This algorithm is not usable for backends in LOG mode. uri This algorithm hashes either the left part of the URI (before the question mark) or the whole URI (if the "whole" parameter is present) and divides the hash value by the total weight of the running servers. The result designates which server will receive the request. This ensures that the same URI will always be directed to the same server as long as no server goes up or down. This is used with proxy caches and anti-virus proxies in order to maximize the cache hit rate. Note that this algorithm may only be used in an HTTP backend. This algorithm is static by default, which means that changing a server's weight on the fly will have no effect, but this can be changed using "hash-type". This algorithm supports two optional parameters "len" and "depth", both followed by a positive integer number. These options may be helpful when it is needed to balance servers based on the beginning of the URI only. The "len" parameter indicates that the algorithm should only consider that many characters at the beginning of the URI to compute the hash. Note that having "len" set to 1 rarely makes sense since most URIs start with a leading "/". The "depth" parameter indicates the maximum directory depth to be used to compute the hash. One level is counted for each slash in the request. If both parameters are specified, the evaluation stops when either is reached. A "path-only" parameter indicates that the hashing key starts at the first '/' of the path. This can be used to ignore the authority part of absolute URIs, and to make sure that HTTP/1 and HTTP/2 URIs will provide the same hash. See also the "hash" option above. url_param The URL parameter specified in argument will be looked up in the query string of each HTTP GET request. If the modifier "check_post" is used, then an HTTP POST request entity will be searched for the parameter argument, when it is not found in a query string after a question mark ('?') in the URL. The message body will only start to be analyzed once either the advertised amount of data has been received or the request buffer is full. In the unlikely event that chunked encoding is used, only the first chunk is scanned. Parameter values separated by a chunk boundary, may be randomly balanced if at all. This keyword used to support an optional parameter which is now ignored. If the parameter is found followed by an equal sign ('=') and a value, then the value is hashed and divided by the total weight of the running servers. The result designates which server will receive the request. This is used to track user identifiers in requests and ensure that a same user ID will always be sent to the same server as long as no server goes up or down. If no value is found or if the parameter is not found, then a round robin algorithm is applied. Note that this algorithm may only be used in an HTTP backend. This algorithm is static by default, which means that changing a server's weight on the fly will have no effect, but this can be changed using "hash-type". See also the "hash" option above. hdr() The HTTP header will be looked up in each HTTP request. Just as with the equivalent ACL 'hdr()' function, the header name in parenthesis is not case sensitive. If the header is absent or if it does not contain any value, the roundrobin algorithm is applied instead. An optional 'use_domain_only' parameter is available, for reducing the hash algorithm to the main domain part with some specific headers such as 'Host'. For instance, in the Host value "haproxy.1wt.eu", only "1wt" will be considered. This algorithm is static by default, which means that changing a server's weight on the fly will have no effect, but this can be changed using "hash-type". See also the "hash" option above. random random() A random number will be used as the key for the consistent hashing function. This means that the servers' weights are respected, dynamic weight changes immediately take effect, as well as new server additions. Random load balancing can be useful with large farms or when servers are frequently added or removed as it may avoid the hammering effect that could result from roundrobin or leastconn in this situation. The hash-balance-factor directive can be used to further improve fairness of the load balancing, especially in situations where servers show highly variable response times. When an argument is present, it must be an integer value one or greater, indicating the number of draws before selecting the least loaded of these servers. It was indeed demonstrated that picking the least loaded of two servers is enough to significantly improve the fairness of the algorithm, by always avoiding to pick the most loaded server within a farm and getting rid of any bias that could be induced by the unfair distribution of the consistent list. Higher values N will take away N-1 of the highest loaded servers at the expense of performance. With very high values, the algorithm will converge towards the leastconn's result but much slower. In addition, for large server farms with very low loads (or perfect balance), comparing loads will often lead to a tie, so in case of equal loads between all measured servers, their request rate over the last second are compared, which allows to better balance server usage over time in the same spirit as roundrobin does, and smooth consistent hash unfairness. The default value is 2, which generally shows very good distribution and performance. For large farms with low loads (less than a few requests per second per server), it may help to raise it to 3 or even 4. This algorithm is also known as the Power of Two Random Choices and is described here: http://www.eecs.harvard.edu/~michaelm/postscripts/handbook2001.pdf For backends in LOG mode, the number of draws is ignored and a single random is picked since there is no notion of server load. Random log balancing can be useful with large farms or when servers are frequently added or removed from the pool of available servers as it may avoid the hammering effect that could result from roundrobin in this situation. rdp-cookie rdp-cookie() The RDP cookie (or "mstshash" if omitted) will be looked up and hashed for each incoming TCP request. Just as with the equivalent ACL 'req.rdp_cookie()' function, the name is not case-sensitive. This mechanism is useful as a degraded persistence mode, as it makes it possible to always send the same user (or the same session ID) to the same server. If the cookie is not found, the normal roundrobin algorithm is used instead. Note that for this to work, the frontend must ensure that an RDP cookie is already present in the request buffer. For this you must use 'tcp-request content accept' rule combined with a 'req.rdp_cookie_cnt' ACL. This algorithm is static by default, which means that changing a server's weight on the fly will have no effect, but this can be changed using "hash-type". See also the "hash" option above. log-hash Takes a comma-delimited list of converters in argument. These converters are applied in sequence to the input log message, and the result will be cast as a string then hashed according to the configured hash-type. The resulting hash will be used to select the destination server among the ones declared in the log backend. The goal of this algorithm is to be able to extract a key within the final log message using string converters and then be able to stick to the same server thanks to the hash. Only "map-based" hashes are supported for now. This algorithm is only usable for backends in LOG mode, for others, please use "hash" instead. sticky Tries to stick to the same server as much as possible. The first server in the list of available servers receives all the log messages. When the server goes DOWN, the next server in the list takes its place. When a previously DOWN server goes back UP it is added at the end of the list so that the sticky server doesn't change until it becomes DOWN. is an optional list of arguments which may be needed by some algorithms. Right now, only "url_param", "uri" and "log-hash" support an optional argument. ``` 当后端未设置其他算法、模式或选项时,其负载均衡算法默认为“random”。每个后端的算法只能设置一次。 对于需要同一连接的认证方案(如 NTLM),不得使用基于 URI 的算法,否则后续请求可能被路由至不同的后端服务器,从而破坏 NTLM 所依赖的无效假设。 TCP/HTTP 示例: ```text 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 balance hash req.cookie(clientid) balance hash var(req.client_id) balance hash req.hdr_ip(x-forwarded-for,-1),ipmask(24) ``` 日志后端示例: ```text global log backend@mylog-rrb local0 # send all logs to mylog-rrb backend log backend@mylog-hash local0 # send all logs to mylog-hash backend backend mylog-rrb mode log balance roundrobin server s1 udp@127.0.0.1:514 # will receive 50% of log messages server s2 udp@127.0.0.1:514 backend mylog-hash mode log # extract "METHOD URL PROTO" at the end of the log message, # and let haproxy hash it so that log messages generated from # similar requests get sent to the same syslog server: balance log-hash 'field(-2,\")' # server list here server s1 127.0.0.1:514 #... ``` 请注意:在使用 "check_post" 扩展与 "url_param" 时,必须考虑以下注意事项和限制: - all POST requests are eligible for consideration, because there is no way to determine if the parameters will be found in the body or entity which may contain binary data. Therefore another method may be required to restrict consideration of POST requests that have no URL parameters in the body. (see acl http_end) - using a `` value larger than the request buffer size does not make sense and is useless. The buffer size is set at build time, and defaults to 16 kB. - Content-Encoding is not supported, the parameter search will probably fail; and load balancing will fall back to Round Robin. - Expect: 100-continue is not supported, load balancing will fall back to Round Robin. - Transfer-Encoding (RFC7230 3.3.1) is only supported in the first chunk. If the entire parameter value is not present in the first chunk, the selection of server is undefined (actually, defined by how little actually appeared in the first chunk). - This feature does not support generation of a 100, 411 or 501 response. - In some cases, requesting "check_post" MAY attempt to scan the entire contents of a message body. Scanning normally terminates when linear white space or control characters are found, indicating the end of what might be a URL parameter list. This is probably not a concern with SGML type message bodies. 另请参阅: "dispatch"、"cookie"、"transparent"、"hash-type"。 **`be-unpublished`** ```haproxy be-unpublished ``` 指示后端以未发布状态启动。 可用于以下上下文:tcp、http、log 可出现在以下段中:defaults \| frontend \| listen \| backend no \| no \| yes \| yes 使用此指令后,其他代理中引用当前代理的 `use_backend` 和 `default_backend` 规则会被忽略,并继续评估后续的内容切换规则。不过,`force-be-switch` 规则可以绕过这一限制。 该状态与禁用状态类似,但有几点不同。首先,未发布的后端仍会完整初始化,包括继续运行服务器健康检查。其次,可通过 CLI 的 `publish backend` 命令将后端公开发布。详见管理手册。 另请参阅:`force-be-switch` **`bind [
]: [, ...] [param*]`** ```haproxy bind [
]: [, ...] [param*] bind / [, ...] [param*] ``` 在前端中定义一个或多个监听地址和/或端口。 可用于以下上下文:tcp、http 可出现在以下段中:defaults \| frontend \| listen \| backend 否 \| 是 \| 是 \| 否 参数: ```text
is optional and can be a host name, an IPv4 address, an IPv6 address, or '*'. It designates the address the frontend will listen on. If unset, all IPv4 addresses of the system will be listened on. The same will apply for '*' or the system's special address "0.0.0.0". The IPv6 equivalent is '::'. Note that for UDP, specific OS features are required when binding on multiple addresses to ensure the correct network interface and source address will be used on response. In other way, for QUIC listeners only bind on multiple addresses if running with a modern enough systems. Optionally, an address family prefix may be used before the address to force the family regardless of the address format, which can be useful to specify a path to a unix socket with no slash ('/'). Currently supported prefixes are: - 'ipv4@' -> address is always IPv4 - 'ipv6@' -> address is always IPv6 - 'udp@' -> address is resolved as IPv4 or IPv6 and protocol UDP is used. Currently those listeners are supported only in log-forward sections. - 'udp4@' -> address is always IPv4 and protocol UDP is used. Currently those listeners are supported only in log-forward sections. - 'udp6@' -> address is always IPv6 and protocol UDP is used. Currently those listeners are supported only in log-forward sections. - 'unix@' -> address is a path to a local unix socket - 'abns@' -> address is in abstract namespace (Linux only). - 'abnsz@' -> address is in abstract namespace (Linux only) but it is explicitly zero-terminated. This means no \0 padding is used to complete sun_path. It is useful to interconnect with programs that don't implement the default abns naming logic that haproxy uses. - 'fd@' -> use file descriptor inherited from the parent. The fd must be bound and may or may not already be listening. - 'sockpair@'-> like fd@ but you must use the fd of a connected unix socket or of a socketpair. The bind waits to receive a FD over the unix socket and uses it as if it was the FD of an accept(). Should be used carefully. - 'quic4@' -> address is resolved as IPv4 and protocol UDP is used. Note that to achieve the best performance with a large traffic you should keep "tune.quic.fe.sock-per-conn default-on". Else QUIC connections will be multiplexed over the listener socket. Another alternative would be to duplicate QUIC listener instances over several threads, for example using "shards" keyword to at least reduce thread contention. - 'quic6@' -> address is resolved as IPv6 and protocol UDP is used. The performance note for QUIC over IPv4 applies as well. - 'rhttp@' [ EXPERIMENTAL ] -> used for reverse HTTP. Address must be a server with the format '/'. The server will be used to instantiate connections to a remote address. The listener will try to maintain "nbconn" connections. This is an experimental features which requires "expose-experimental-directives" on a line before this bind. You may want to reference some environment variables in the address parameter, see section 2.3 about environment variables. is either a unique TCP port, or a port range for which the proxy will accept connections for the IP address specified above. The port is mandatory for TCP listeners. Note that in the case of an IPv6 address, the port is always the number after the last colon (':'). A range can either be: - a numerical port (ex: '80') - a dash-delimited ports range explicitly stating the lower and upper bounds (ex: '2000-2100') which are included in the range. Particular care must be taken against port ranges, because every couple consumes one socket (= a file descriptor), so it's easy to consume lots of descriptors with a simple range, and to run out of sockets. Also, each couple must be used only once among all instances running on a same system. Please note that binding to ports lower than 1024 generally require particular privileges to start the program, which are independent of the 'uid' parameter. is a UNIX socket path beginning with a slash ('/'). This is alternative to the TCP listening port. HAProxy will then receive UNIX connections on the socket located at this place. The path must begin with a slash and by default is absolute. It can be relative to the prefix defined by "unix-bind" in the global section. Note that the total length of the prefix followed by the socket path cannot exceed some system limits for UNIX sockets, which commonly are set to 107 characters. is a list of parameters common to all sockets declared on the same line. These numerous parameters depend on OS and build options and have a complete section dedicated to them. Please refer to section 5 to for more details. ``` 可以指定以逗号分隔的地址:端口组合列表。前端将在此列出的所有地址上监听。前端可监听的地址和端口数量没有固定限制,同时前端中“bind”语句的数量也没有限制。 示例: ```text listen http_proxy bind:80,:443 bind 10.0.0.1:10080,10.0.0.1:10443 bind /var/run/ssl-frontend.sock user root mode 600 accept-proxy listen http_https_proxy bind:80 bind:443 ssl crt /etc/haproxy/site.pem listen http_https_proxy_explicit bind ipv6@:80 bind ipv4@public_ssl:443 ssl crt /etc/haproxy/site.pem bind unix@ssl-frontend.sock user root mode 600 accept-proxy listen external_bind_app1 bind "fd@${FD_APP1}" listen h3_quic_proxy bind quic4@10.0.0.1:8888 ssl crt /etc/mycrt ``` 请注意:关于 Linux 的抽象命名空间套接字,“abns” HAProxy 套接字使用 sun_path 的完整长度作为地址长度。其他一些程序(如 socat)默认仅使用字符串长度。如需使 socat 的抽象套接字定义与 HAProxy 兼容,请向 socat 的任意抽象套接字定义传递选项 ",unix-tightsocklen=0",或改用 "abnsz" HAProxy 套接字族。 另请参阅:“source”、“option forwardfor”、“unix-bind”以及 PROXY 协议文档,以及关于绑定选项的[第 5 节](/zh/docs/haproxy/bind-and-server-options/)。 **`capture cookie len `** ```haproxy capture cookie len ``` 捕获并记录请求和响应中的 Cookie。 可以用于以下上下文:http 可出现在以下段中:defaults \| frontend \| listen \| backend 否 \| 是 \| 是 \| 否 参数: ```text is the beginning of the name of the cookie to capture. In order to match the exact name, simply suffix the name with an equal sign ('='). The full name will appear in the logs, which is useful with application servers which adjust both the cookie name and value (e.g. ASPSESSIONXXX). is the maximum number of characters to report in the logs, which include the cookie name, the equal sign and the value, all in the standard "name=value" form. The string will be truncated on the right if it exceeds . ``` 仅捕获第一个 Cookie。同时监控“cookie”请求头和“set-cookie”响应头。此功能特别适用于检查应用程序缺陷导致的用户间会话交叉或会话窃取问题,因为通常情况下用户的 Cookie 仅在登录页面发生变更。 当客户端未提供 Cookie 时,相关日志列将报告“-”。当请求未导致服务器分配 Cookie 时,响应列将报告“-”。 捕获操作仅在前端执行,因为必须确保某个前端的日志格式不随后端变化而改变。此行为未来可能会调整。请注意,一个前端中只能存在一条“capture cookie”语句。捕获的最大长度由全局 "tune.http.cookielen" 设置决定,默认值为 63 个字符。无法在“defaults”段中指定捕获。 示例: ```text capture cookie ASPSESSION len 32 ``` 另请参阅:“捕获请求头”、“捕获响应头”,以及关于日志记录的 [第 8 节](/zh/docs/haproxy/configuration-logging/)。 **`capture request header len `** ```haproxy capture request header len ``` 捕获并记录指定请求头的最后一次出现。 可以用于以下上下文:http 可出现在以下段中:defaults \| frontend \| listen \| backend 否 \| 是 \| 是 \| 否 参数: ```text is the name of the header to capture. The header names are not case-sensitive, but it is a common practice to write them as they appear in the requests, with the first letter of each word in upper case. The header name will not appear in the logs, only the value is reported, but the position in the logs is respected. is the maximum number of characters to extract from the value and report in the logs. The string will be truncated on the right if it exceeds . ``` 捕获最后一个出现的头的完整值。该值将被添加到日志中,用大括号('{}')括起。若捕获多个头,它们将按配置中声明的顺序以竖线('\|')分隔,并依次出现。不存在的头将被记录为空字符串。请求头捕获的常见用途包括:在虚拟主机环境中捕获“Host”字段,在支持上传时捕获“Content-length”,通过“User-agent”快速区分真实用户与机器人,以及在代理环境中捕获“X-Forwarded-For”以确定请求来源。 请注意,捕获如 "User-agent" 等头时,日志中可能包含空格,这会使日志分析更加困难。因此,如果已知日志解析器不够智能,无法依赖大括号解析,请谨慎选择记录的内容。 对捕获的请求头数量和长度均无限制,但建议保持较低数量以降低每流的内存使用量。为确保同一前端的日志格式一致,头捕获只能在前端段中声明。无法在“defaults”段中指定捕获。 示例: ```text capture request header Host len 15 capture request header X-Forwarded-For len 15 capture request header Referer len 15 ``` 另请参阅:“捕获 cookie”、“捕获响应头”,以及关于日志记录的 [第 8 节](/zh/docs/haproxy/configuration-logging/)。 **`capture response header len `** ```haproxy capture response header len ``` 捕获并记录指定响应头的最后一次出现。 可以用于以下上下文:http 可出现在以下段中:defaults \| frontend \| listen \| backend 否 \| 是 \| 是 \| 否 参数: ```text is the name of the header to capture. The header names are not case-sensitive, but it is a common practice to write them as they appear in the response, with the first letter of each word in upper case. The header name will not appear in the logs, only the value is reported, but the position in the logs is respected. is the maximum number of characters to extract from the value and report in the logs. The string will be truncated on the right if it exceeds . ``` 最后一次出现的头字段的完整值将被捕获。捕获结果将被添加到日志中,位于捕获的请求头之后,用大括号('{}')括起。若捕获了多个头字段,它们将以竖线('\|')分隔,并按配置中声明的顺序出现。不存在的头字段将被记录为空字符串。响应头捕获的常见用途包括“Content-length”头,用于指示预期返回的字节数,以及“Location”头,用于追踪重定向。 对响应头的捕获数量和长度均无限制,但建议保持较低数量以控制每流的内存使用量。为确保同一前端的日志格式一致,头捕获只能在前端中声明。无法在“defaults”段中指定捕获。 示例: ```text capture response header Content-length len 9 capture response header Location len 15 ``` 另请参阅:“捕获 cookie”、“捕获请求头”,以及关于日志记录的 [第 8 节](/zh/docs/haproxy/configuration-logging/)。 **`clitcpka-cnt `** ```haproxy clitcpka-cnt ``` 设置 TCP 在客户端侧丢弃连接前应发送的最大保活探测次数。 可用于以下上下文:tcp、http、log 可出现在以下段中:defaults \| frontend \| listen \| backend yes \| yes \| yes \| no 参数: ```text is the maximum number of keepalive probes. ``` 此关键字对应套接字选项 TCP_KEEPCNT。若未指定此关键字,则使用系统级 TCP 参数(tcp_keepalive_probes)。该设置的可用性取决于操作系统。已知其在 Linux 上可用。 另请参见:“option clitcpka”、“clitcpka-idle”、“clitcpka-intvl”。 **`clitcpka-idle `** ```haproxy clitcpka-idle ``` 设置连接在 TCP 开始发送保活探测前需保持空闲的时间,若启用,则在客户端侧发送 TCP 保活数据包。 可用于以下上下文:tcp、http 可出现在以下段中:defaults \| frontend \| listen \| backend yes \| yes \| yes \| no 参数: ```text is the time the connection needs to remain idle before TCP starts sending keepalive probes. It is specified in seconds by default, but can be in any other unit if the number is suffixed by the unit, as explained at the top of this document. ``` 此关键字对应套接字选项 TCP_KEEPIDLE。若未指定此关键字,则使用系统级 TCP 参数(tcp_keepalive_time)。该设置的可用性取决于操作系统。已知其在 Linux 上可用。 另请参见:“option clitcpka”、“clitcpka-cnt”、“clitcpka-intvl”。 **`clitcpka-intvl `** ```haproxy clitcpka-intvl ``` 设置客户端侧单个 keepalive 探测之间的时间间隔。 可用于以下上下文:tcp、http 可出现在以下段中:defaults \| frontend \| listen \| backend yes \| yes \| yes \| no 参数: ```text is the time between individual keepalive probes. It is specified in seconds by default, but can be in any other unit if the number is suffixed by the unit, as explained at the top of this document. ``` 此关键字对应套接字选项 TCP_KEEPINTVL。若未指定此关键字,则使用系统级 TCP 参数(tcp_keepalive_intvl)。该设置的可用性取决于操作系统。已知其在 Linux 上可用。 另请参见:“option clitcpka”、“clitcpka-cnt”、“clitcpka-idle”。 **`compression algo ...`** ```haproxy compression algo ... compression algo-req compression algo-res compression type ... ``` 启用 HTTP 压缩。 可以用于以下上下文:http 可出现在以下段中:defaults \| frontend \| listen \| backend yes \| yes \| yes \| yes 参数: ```text algo is followed by the list of supported compression algorithms for responses (legacy keyword) algo-req is followed by compression algorithm for request (only one is provided). algo-res is followed by the list of supported compression algorithms for responses. type is followed by the list of MIME types that will be compressed for responses (legacy keyword). type-req is followed by the list of MIME types that will be compressed for requests. type-res is followed by the list of MIME types that will be compressed for responses. ``` 当前支持的算法如下: ```text identity this is mostly for debugging, and it was useful for developing the compression feature. Identity does not apply any change on data. gzip applies gzip compression. This setting is only available when support for zlib or libslz was built in. deflate same as "gzip", but with deflate algorithm and zlib format. Note that this algorithm has ambiguous support on many browsers and no support at all from recent ones. It is strongly recommended not to use it for anything else than experimentation. This setting is only available when support for zlib or libslz was built in. raw-deflate same as "deflate" without the zlib wrapper, and used as an alternative when the browser wants "deflate". All major browsers understand it and despite violating the standards, it is known to work better than "deflate", at least on MSIE and some versions of Safari. Do not use it in conjunction with "deflate", use either one or the other since both react to the same Accept-Encoding token. This setting is only available when support for zlib or libslz was built in. ``` 压缩功能将根据请求头中的 Accept-Encoding 决定是否启用。若设置为 identity,则忽略该请求头。若后端服务器支持 HTTP 压缩,这些指令将无操作:HAProxy 会识别已压缩的响应,不再进行二次压缩。若后端服务器不支持 HTTP 压缩,且请求中包含 Accept-Encoding 头,则 HAProxy 将对匹配的响应进行压缩。 当满足以下任一条件时,压缩功能将被禁用: - 请求未在 "Accept-Encoding" 头中声明支持的压缩算法 - 响应消息的协议版本低于 HTTP/1.1 - HTTP 状态码不是 200、201、202 或 203 之一 - 响应既不包含 "Content-Length" 头,也不包含 "Transfer-Encoding" 头且其最后一个值不是 "chunked" - 响应包含 "Content-Type" 头,且其首个值以 "multipart" 开头 - 响应包含 "Cache-control" 头且其值包含 "no-transform" - User-Agent 匹配 "Mozilla/4",除非其为 MSIE 6 且运行于 XP SP2,或 MSIE 7 及更高版本 - 响应包含 "Content-Encoding" 头,表明响应已压缩(参见压缩卸载) - 响应包含无效的 "ETag" 头或多个 ETag 头 - 负载大小小于最小大小(参见 compression minsize-res) 请注意:压缩功能不会发出 Warning 头。 示例: ```text compression algo gzip compression type text/html text/plain ``` 另请参见:“compression offload”、“compression direction”、“compression minsize-req”和“compression minsize-res” **`compression minsize-req `** ```haproxy compression minsize-req compression minsize-res ``` 设置应用压缩功能的最小负载大小(以字节为单位)。 可以用于以下上下文:http 可出现在以下段中:defaults \| frontend \| listen \| backend yes \| yes \| yes \| yes 小于该大小的负载将不会被压缩,以避免对无法显著受益于压缩的数据造成不必要的 CPU 开销。“minsize-req” 适用于请求,“minsize-res” 适用于响应。默认值为 0。 **`compression offload`** ```haproxy compression offload ``` 使 HAProxy 仅作为压缩卸载器工作。 可以用于以下上下文:http 可出现在以下段中:defaults \| frontend \| listen \| backend 否 \| 是 \| 是 \| 是 offload 设置会使 HAProxy 移除 Accept-Encoding 头,以防止后端服务器对响应进行压缩。强烈建议不要执行此操作,因为这意味着所有压缩工作都将集中于 HAProxy 所在的单一节点上。然而在某些部署场景中,HAProxy 可能位于存在缺陷的网关前端,而该网关的 HTTP 压缩实现存在缺陷且无法关闭。在此情况下,HAProxy 可用于防止该网关发出无效负载。在这种场景下,仅在配置中移除头信息无效,因为该操作在头信息被解析前执行,从而阻止了 HAProxy 自身进行压缩。此时应使用 offload 设置。 如果在 defaults 段中使用此设置,将发出警告并忽略该选项。 另请参见:“压缩类型”、“压缩算法”、“压缩方向” **`compression direction (deprecated)`** ```haproxy compression direction (deprecated) ``` 使 HAProxy 能够压缩请求和响应。有效值为 "request",仅压缩请求;"response",仅压缩响应;或 "both",当需要同时压缩请求和响应时使用。默认值为 "response"。 该指令仅在启用旧版“过滤器压缩”时才相关,因为当显式使用 comp-req 和 comp-res 过滤器时,压缩方向已冗余。 可以用于以下上下文:http 另请参阅:"compression type"、"compression algo"、"compression offload" **`cookie [ rewrite | insert | prefix ] [ indirect ] [ nocache ]`** ```haproxy cookie [ rewrite | insert | prefix ] [ indirect ] [ nocache ] [ postonly ] [ preserve ] [ httponly ] [ secure ] [ domain ]* [ maxidle ] [ maxlife ] [ dynamic ] [ attr ]* ``` 在后端中启用基于 Cookie 的持久性。 可以用于以下上下文:http 可出现在以下段中:defaults \| frontend \| listen \| backend yes \| no \| yes \| yes 参数: ```text is the name of the cookie which will be monitored, modified or inserted in order to bring persistence. This cookie is sent to the client via a "Set-Cookie" header in the response, and is brought back by the client in a "Cookie" header in all requests. Special care should be taken to choose a name which does not conflict with any likely application cookie. Also, if the same backends are subject to be used by the same clients (e.g. HTTP/HTTPS), care should be taken to use different cookie names between all backends if persistence between them is not desired. rewrite This keyword indicates that the cookie will be provided by the server and that HAProxy will have to modify its value to set the server's identifier in it. This mode is handy when the management of complex combinations of "Set-cookie" and "Cache-control" headers is left to the application. The application can then decide whether or not it is appropriate to emit a persistence cookie. Since all responses should be monitored, this mode doesn't work in HTTP tunnel mode. Unless the application behavior is very complex and/or broken, it is advised not to start with this mode for new deployments. This keyword is incompatible with "insert" and "prefix". insert This keyword indicates that the persistence cookie will have to be inserted by HAProxy in server responses if the client did not already have a cookie that would have permitted it to access this server. When used without the "preserve" option, if the server emits a cookie with the same name, it will be removed before processing. For this reason, this mode can be used to upgrade existing configurations running in the "rewrite" mode. The cookie will only be a session cookie and will not be stored on the client's disk. By default, unless the "indirect" option is added, the server will see the cookies emitted by the client. Due to caching effects, it is generally wise to add the "nocache" or "postonly" keywords (see below). The "insert" keyword is not compatible with "rewrite" and "prefix". prefix This keyword indicates that instead of relying on a dedicated cookie for the persistence, an existing one will be completed. This may be needed in some specific environments where the client does not support more than one single cookie and the application already needs it. In this case, whenever the server sets a cookie named , it will be prefixed with the server's identifier and a delimiter. The prefix will be removed from all client requests so that the server still finds the cookie it emitted. Since all requests and responses are subject to being modified, this mode doesn't work with tunnel mode. The "prefix" keyword is not compatible with "rewrite" and "insert". Note: it is highly recommended not to use "indirect" with "prefix", otherwise server cookie updates would not be sent to clients. indirect When this option is specified, no cookie will be emitted to a client which already has a valid one for the server which has processed the request. If the server sets such a cookie itself, it will be removed, unless the "preserve" option is also set. In "insert" mode, this will additionally remove cookies from the requests transmitted to the server, making the persistence mechanism totally transparent from an application point of view. Note: it is highly recommended not to use "indirect" with "prefix", otherwise server cookie updates would not be sent to clients. nocache This option is recommended in conjunction with the insert mode when there is a cache between the client and HAProxy, as it ensures that a cacheable response will be tagged non-cacheable if a cookie needs to be inserted. This is important because if all persistence cookies are added on a cacheable home page for instance, then all customers will then fetch the page from an outer cache and will all share the same persistence cookie, leading to one server receiving much more traffic than others. See also the "insert" and "postonly" options. postonly This option ensures that cookie insertion will only be performed on responses to POST requests. It is an alternative to the "nocache" option, because POST responses are not cacheable, so this ensures that the persistence cookie will never get cached. Since most sites do not need any sort of persistence before the first POST which generally is a login request, this is a very efficient method to optimize caching without risking to find a persistence cookie in the cache. See also the "insert" and "nocache" options. preserve This option may only be used with "insert" and/or "indirect". It allows the server to emit the persistence cookie itself. In this case, if a cookie is found in the response, HAProxy will leave it untouched. This is useful in order to end persistence after a logout request for instance. For this, the server just has to emit a cookie with an invalid value (e.g. empty) or with a date in the past. By combining this mechanism with the "disable-on-404" check option, it is possible to perform a completely graceful shutdown because users will definitely leave the server after they logout. httponly This option tells HAProxy to add an "HttpOnly" cookie attribute when a cookie is inserted. This attribute is used so that a user agent doesn't share the cookie with non-HTTP components. Please check RFC6265 for more information on this attribute. secure This option tells HAProxy to add a "Secure" cookie attribute when a cookie is inserted. This attribute is used so that a user agent never emits this cookie over non-secure channels, which means that a cookie learned with this flag will be presented only over SSL/TLS connections. Please check RFC6265 for more information on this attribute. domain This option allows to specify the domain at which a cookie is inserted. It requires exactly one parameter: a valid domain name. If the domain begins with a dot, the browser is allowed to use it for any host ending with that name. It is also possible to specify several domain names by invoking this option multiple times. Some browsers might have small limits on the number of domains, so be careful when doing that. For the record, sending 10 domains to MSIE 6 or Firefox 2 works as expected. maxidle This option allows inserted cookies to be ignored after some idle time. It only works with insert-mode cookies. When a cookie is sent to the client, the date this cookie was emitted is sent too. Upon further presentations of this cookie, if the date is older than the delay indicated by the parameter (in seconds), it will be ignored. Otherwise, it will be refreshed if needed when the response is sent to the client. This is particularly useful to prevent users who never close their browsers from remaining for too long on the same server (e.g. after a farm size change). When this option is set and a cookie has no date, it is always accepted, but gets refreshed in the response. This maintains the ability for admins to access their sites. Cookies that have a date in the future further than 24 hours are ignored. Doing so lets admins fix timezone issues without risking kicking users off the site. maxlife This option allows inserted cookies to be ignored after some life time, whether they're in use or not. It only works with insert mode cookies. When a cookie is first sent to the client, the date this cookie was emitted is sent too. Upon further presentations of this cookie, if the date is older than the delay indicated by the parameter (in seconds), it will be ignored. If the cookie in the request has no date, it is accepted and a date will be set. Cookies that have a date in the future further than 24 hours are ignored. Doing so lets admins fix timezone issues without risking kicking users off the site. Contrary to maxidle, this value is not refreshed, only the first visit date counts. Both maxidle and maxlife may be used at the time. This is particularly useful to prevent users who never close their browsers from remaining for too long on the same server (e.g. after a farm size change). This is stronger than the maxidle method in that it forces a redispatch after some absolute delay. dynamic Activate dynamic cookies. When used, a session cookie is dynamically created for each server, based on the IP and port of the server, and a secret key, specified in the "dynamic-cookie-key" backend directive. The cookie will be regenerated each time the IP address change, and is only generated for IPv4/IPv6. attr This option tells HAProxy to add an extra attribute when a cookie is inserted. The attribute value can contain any characters except control ones or ";". This option may be repeated. ``` 每个 HTTP 后端只能有一个持久性 cookie,该 cookie 可在 defaults 段中声明。cookie 的值将为服务器语句中 "cookie" 关键字后指定的值。若未为某个服务器声明 cookie,则不会设置 cookie。 示例: ```text cookie JSESSIONID prefix cookie SRV insert indirect nocache cookie SRV insert postonly indirect cookie SRV insert indirect nocache maxidle 30m maxlife 8h ``` 另请参见:“balance source”、“capture cookie”、“server”和“ignore-persist”。 **`declare capture [ request | response ] len `** ```haproxy declare capture [ request | response ] len ``` 声明一个捕获槽。 可用于以下上下文:tcp、http 可出现在以下段中:defaults \| frontend \| listen \| backend 否 \| 是 \| 是 \| 否 参数: ```text is the length allowed for the capture. ``` 此声明仅可在前端或 listen 段中使用,但预留的槽位可在后端中使用。“request”关键字用于为请求分配一个捕获槽位,“response”关键字用于为响应分配一个捕获槽位。 另请参阅:“capture-req”、“capture-res”(样本转换器)、"capture.req.hdr"、"capture.res.hdr"(样本提取)、“http-request capture”和“http-response capture”。 **`default-server [param*]`** ```haproxy default-server [param*] ``` 更改后端中服务器的默认选项 可用于以下上下文:tcp、http 可出现在以下段中:defaults \| frontend \| listen \| backend yes \| no \| yes \| yes 参数: ```text is a list of parameters for this server. The "default-server" keyword accepts an important number of options and has a complete section dedicated to it. Please refer to section 5 for more details. ``` 示例: ```text default-server inter 1000 weight 13 ``` 另请参阅:“服务器”以及 [第 5 节](/zh/docs/haproxy/bind-and-server-options/) 中关于服务器选项的内容 **`default_backend `** ```haproxy default_backend ``` 当未匹配任何 "use_backend" 规则时,指定要使用的后端。 可用于以下上下文:tcp、http 可出现在以下段中:defaults \| frontend \| listen \| backend yes \| yes \| yes \| no 参数: ```text is the name of the backend to use. ``` 使用 "use_backend" 关键字在前端与后端之间进行内容切换时,通常需要明确指定当无规则匹配时将使用的后端。这通常是动态后端,用于捕获所有未确定的请求。 如果后端被禁用或未发布,针对该后端的 default_backend 规则将被忽略,流处理将继续在原始代理上进行。 示例: ```text use_backend dynamic if url_dyn use_backend static if url_css url_img extension_img default_backend dynamic ``` 参见:"use_backend" **`description `** ```haproxy description ``` 描述一个 listen、frontend 或 backend。 可用于以下上下文:tcp、http、log 可出现在以下段中:defaults \| frontend \| listen \| backend 否 \| 是 \| 是 \| 是 参数:string 允许在 HAProxy HTML 统计信息页面中为相关对象添加描述语句。描述内容将显示在所描述对象名称的右侧。`` 参数中无需转义空格。 **`disabled`** ```haproxy disabled ``` 禁用代理、前端或后端。 可用于以下上下文:tcp、http、log 可出现在以下段中:defaults \| frontend \| listen \| backend yes \| yes \| yes \| yes 参数:无 “disabled” 关键字用于禁用实例,主要用于释放监听端口或临时停用服务。实例仍将被创建并进行配置检查,但将以“已停止”状态创建,并在统计信息中显示为已停止状态。该实例不会接收任何流量,也不会发送健康检查或日志。可以通过在“defaults”段中添加“disabled”关键字,一次性禁用多个实例。 默认情况下,无法选择已禁用的后端进行内容切换。然而,当使用 "force-be-switch" 时,部分流量可忽略此限制。 另请参阅: "enabled","force-be-switch" **`dispatch
: (deprecated)`** ```haproxy dispatch
: (deprecated) ``` 设置默认服务器地址 可用于以下上下文:tcp、http 可出现在以下段中:defaults \| frontend \| listen \| backend 参数: ```text
is the IPv4 address of the default server. Alternatively, a resolvable hostname is supported, but this name will be resolved during start-up. is a mandatory port specification. All connections will be sent to this port, and it is not permitted to use port offsets as is possible with normal servers. ``` dispatch 指令 "dispatch" 指令用于指定在无法连接到其他服务器时使用的默认服务器。过去,该指令曾用于将非持久连接转发至辅助负载均衡器。由于其语法简单,也曾被用于实现简单的 TCP 中继。为提高配置清晰度,建议不再使用该指令,而应改用 "server" 指令。 该关键字已在 3.3 版本中弃用,并将在 3.5 版本中移除,原因在于存在一些内部限制(例如不支持 SSL 或空闲连接等)。使用该关键字将发出警告,可通过在全局段启用指令 "expose-deprecated-directives" 来静默此警告。 正确做法是,不使用该指令时,只需声明一个地址和端口相同的服务器。如果“dispatch”指令与其他服务器混合使用,则应将这些服务器的权重配置为零,以确保负载均衡算法永远不会选择它们。 示例: ```text backend deprecated_setup dispatch 192.168.100.100:80 # external load balancer's address server s1 192.168.100.1:80 cookie S1 check server s2 192.168.100.2:80 cookie S2 check backend modern_setup server external_lb 192.168.100.100:80 server s1 192.168.100.1:80 cookie S1 check weight 0 server s2 192.168.100.2:80 cookie S2 check weight 0 ``` 另请参见:服务器 **`dynamic-cookie-key `** ```haproxy dynamic-cookie-key ``` 为后端设置动态 Cookie 密钥。 可以用于以下上下文:http 可出现在以下段中:defaults \| frontend \| listen \| backend yes \| no \| yes \| yes 参数:用于的密钥。 当启用动态 cookie(参见 cookie 指令中的 "dynamic" 选项)时,将为每个服务器创建一个动态 cookie(除非在 "server" 指令中显式指定),该 cookie 通过服务器的 IP 地址、TCP 端口和密钥的哈希值生成。这样可确保在多个负载均衡器之间实现会话持久性,即使服务器动态添加或移除也能保持会话连续。 **`enabled`** ```haproxy enabled ``` 启用代理、前端或后端。 可用于以下上下文:tcp、http、log 可出现在以下段中:defaults \| frontend \| listen \| backend yes \| yes \| yes \| yes 参数:无 "enabled" 关键字用于显式启用实例,当默认值已设为 "disabled" 时使用。此用法极为罕见。 另请参见: "be-unpublished"、"disabled" **`errorfile `** ```haproxy errorfile ``` 返回文件内容,而非 HAProxy 生成的错误信息 可以用于以下上下文:http 可出现在以下段中:defaults \| frontend \| listen \| backend yes \| yes \| yes \| yes 参数: ```text is the HTTP status code. Currently, HAProxy is capable of generating codes 200, 400, 401, 403, 404, 405, 407, 408, 410, 413, 414, 425, 429, 431, 500, 501, 502, 503, and 504. designates a file containing the full HTTP response. It is recommended to follow the common practice of appending ".http" to the filename so that people do not confuse the response with HTML error pages, and to use absolute paths, since files are read before any chroot is performed. ``` 必须理解,该关键字并非用于重写服务器返回的错误,而是用于重写 HAProxy 检测并返回的错误。这也是为何支持的错误列表被限制在较小的集合中。 状态码 200 在响应匹配 "monitor-uri" 规则的请求时发出。 HAProxy 启动时会解析这些文件,且必须符合 HTTP 规范。文件大小不得超过配置的缓冲区大小(BUFSIZE),通常为 16 kB,否则将返回内部错误。建议不要引用本地内容(例如图片),以避免在所有服务器均不可用时,客户端与 HAProxy 之间产生循环,导致返回错误而非图片。最后,响应大小不得超过(tune.bufsize - tune.maxrewrite),以确保“http-after-response”规则仍有操作空间(参见 "tune.maxrewrite")。 文件在读取配置的同时被加载并保留在内存中。因此,即使进程已执行 chroot,错误仍会持续返回,且在进程运行期间不会考虑文件的任何变更。开发这些文件的一种简单方法是将其与 403 状态码关联,并查询一个被阻止的 URL。 另请参见: "http-error", "errorloc", "errorloc302", "errorloc303" 示例: ```text errorfile 400 /etc/haproxy/errorfiles/400badreq.http errorfile 408 /dev/null # work around Chrome pre-connect bug errorfile 403 /etc/haproxy/errorfiles/403forbid.http errorfile 503 /etc/haproxy/errorfiles/503sorry.http ``` **`errorfiles [ ...]`** ```haproxy errorfiles [ ...] ``` 导入在 `` http-errors 段中定义的错误文件,可全部或部分导入。 可以用于以下上下文:http 可出现在以下段中:defaults \| frontend \| listen \| backend yes \| yes \| yes \| yes 参数: ```text is the name of an existing http-errors section. is a HTTP status code. Several status code may be listed. Currently, HAProxy is capable of generating codes 200, 400, 401, 403, 404, 405, 407, 408, 410, 413, 414, 425, 429, 431, 500, 501, 502, 503, and 504. ``` 在 http-errors 段中定义的名称为 `` 的错误会被导入当前代理。 若未指定状态码,则导入 http-errors 段中的所有错误文件。否则,仅导入与所列状态码关联的错误文件。这些错误文件将覆盖代理中已定义的自定义错误,且可能被后续导入的错误文件覆盖。 在功能上,这与手动使用 "errorfile" 指令声明所有错误文件完全相同。 有关 HTTP 错误的更多信息,请参阅 "http-error"、"errorfile"、"errorloc"、"errorloc302"、"errorloc303" 以及 [第 12.4 节](/zh/docs/haproxy/other-sections/#section-12-4)。 示例: ```text errorfiles generic errorfiles site-1 403 404 ``` **`errorloc `** ```haproxy errorloc errorloc302 ``` 返回 HTTP 重定向至指定 URL,而非 HAProxy 生成的错误 可以用于以下上下文:http 可出现在以下段中:defaults \| frontend \| listen \| backend yes \| yes \| yes \| yes 参数: ```text is the HTTP status code. Currently, HAProxy is capable of generating codes 200, 400, 401, 403, 404, 405, 407, 408, 410, 413, 414, 425, 429, 431, 500, 501, 502, 503, and 504. it is the exact contents of the "Location" header. It may contain either a relative URI to an error page hosted on the same site, or an absolute URI designating an error page on another site. Special care should be given to relative URIs to avoid redirect loops if the URI itself may generate the same error (e.g. 500). ``` 必须理解,该关键字并非用于重写服务器返回的错误,而是用于重写 HAProxy 检测并返回的错误。这也是为何支持的错误列表被限制在较小的集合中。 状态码 200 在响应匹配 "monitor-uri" 规则的请求时发出。 请注意,这两个关键字均返回 HTTP 302 状态码,指示客户端使用相同的 HTTP 方法获取指定的 URL。在使用非 GET 方法(如 POST)时,这可能会造成问题,因为发送给客户端的 URL 可能不允许用于除 GET 以外的其他方法。为规避此问题,请使用 "errorloc303",该关键字发送 HTTP 303 状态码,指示客户端必须使用 GET 请求获取该 URL。 另请参阅: "http-error"、"errorfile"、"errorloc303" **`errorloc303 `** ```haproxy errorloc303 ``` 返回 HTTP 重定向至指定 URL,而非 HAProxy 生成的错误 可以用于以下上下文:http 可出现在以下段中:defaults \| frontend \| listen \| backend yes \| yes \| yes \| yes 参数: ```text is the HTTP status code. Currently, HAProxy is capable of generating codes 200, 400, 401, 403, 404, 405, 407, 408, 410, 413, 414, 425, 429, 431, 500, 501, 502, 503, and 504. it is the exact contents of the "Location" header. It may contain either a relative URI to an error page hosted on the same site, or an absolute URI designating an error page on another site. Special care should be given to relative URIs to avoid redirect loops if the URI itself may generate the same error (e.g. 500). ``` 必须理解,该关键字并非用于重写服务器返回的错误,而是用于重写 HAProxy 检测并返回的错误。这也是为何支持的错误列表被限制在较小的集合中。 状态码 200 在响应匹配 "monitor-uri" 规则的请求时发出。 请注意,这两个关键字均返回 HTTP 303 状态码,该码指示客户端使用相同的 HTTP GET 方法获取指定的 URL。这解决了与“errorloc”和 302 状态码相关联的常见问题。尽管可能存在一些在 HTTP/1.1 之前设计的老旧浏览器不支持此行为,但截至目前尚未报告此类问题。 另请参见:"http-error"、"errorfile"、"errorloc"、"errorloc302" **`email-alert from `** ```haproxy email-alert from ``` 声明用于邮件警报信封和头中的发件人地址。此地址即为邮件警报的发送来源。 可用于以下上下文:tcp、http、log 可出现在以下段中:defaults \| frontend \| listen \| backend yes \| yes \| yes \| yes 参数: ```text is the from email address to use when sending email alerts ``` 还要求设置 "email-alert mailers" 和 "email-alert to",若已设置,则为该代理启用邮件告警功能。 参见:“email-alert level”、“email-alert mailers”、“email-alert myhostname”、“email-alert to”,以及关于邮件发送器的[第 12.3 节](/zh/docs/haproxy/other-sections/#section-12-3)。 **`email-alert level `** ```haproxy email-alert level ``` 声明将发送邮件告警的消息最大日志级别。这将作为邮件告警发送的过滤器。 可用于以下上下文:tcp、http、log 可出现在以下段中:defaults \| frontend \| listen \| backend yes \| yes \| yes \| yes 参数: ```text One of the 8 syslog levels: emerg alert crit err warning notice info debug The above syslog levels are ordered from lowest to highest. ``` 默认级别为 alert 还要求设置 "email-alert from"、"email-alert mailers" 和 "email-alert to",若已设置,则为该代理启用邮件告警功能。 当满足以下条件时发送告警: - 未暂停的服务器被标记为不可用,且 `` 的日志级别为 alert 或更低 - 暂停的服务器被标记为不可用,且 `` 的日志级别为 notice 或更低 - 服务器被标记为可用或进入 drain 状态,且 `` 的日志级别为 notice 或更低 - 启用了 "option log-health-checks",`` 的日志级别为 info 或更低,且发生健康检查状态更新 参见:“email-alert from”、“email-alert mailers”、“email-alert myhostname”、“email-alert to”,以及关于邮件发送器的[第 12.3 节](/zh/docs/haproxy/other-sections/#section-12-3)。 **`email-alert mailers `** ```haproxy email-alert mailers ``` 声明用于发送邮件告警的邮件发送器 可用于以下上下文:tcp、http、log 可出现在以下段中:defaults \| frontend \| listen \| backend yes \| yes \| yes \| yes 参数: ```text is the name of the mailers section to send email alerts. ``` 还要求设置 "email-alert from" 和 "email-alert to",若已设置,则为该代理启用邮件告警功能。 参见: "email-alert from"、"email-alert level"、"email-alert myhostname"、"email-alert to",以及关于邮件发送器的[第 12.3 节](/zh/docs/haproxy/other-sections/#section-12-3)。 **`email-alert myhostname `** ```haproxy email-alert myhostname ``` 声明用于与邮件发送器通信时的主机名地址。 可用于以下上下文:tcp、http、log 可出现在以下段中:defaults \| frontend \| listen \| backend yes \| yes \| yes \| yes 参数: ```text is the hostname to use when communicating with mailers ``` 默认情况下,使用系统的主机名。 还要求设置 "email-alert from"、"email-alert mailers" 和 "email-alert to",若已设置,则为该代理启用邮件告警功能。 另请参阅:“email-alert from”、“email-alert level”、“email-alert mailers”、“email-alert to”,以及关于邮件发送器的[第 12.3 节](/zh/docs/haproxy/other-sections/#section-12-3)。 **`email-alert to `** ```haproxy email-alert to ``` 声明邮件警报信封中的收件人地址以及邮件头中的收件人地址。 此地址为邮件警报的发送目标。 可用于以下上下文:tcp、http、log 可出现在以下段中:defaults \| frontend \| listen \| backend yes \| yes \| yes \| yes 参数: ```text is the to email address to use when sending email alerts ``` 还要求设置 "email-alert mailers" 和 "email-alert to",若已设置,则为该代理启用邮件告警功能。 参见: "email-alert from"、"email-alert level"、"email-alert mailers"、"email-alert myhostname",以及关于邮件发送器的 [第 12.3 节](/zh/docs/haproxy/other-sections/#section-12-3)。 **`error-log-format `** ```haproxy error-log-format ``` 指定在前端发生连接错误时所使用的日志格式字符串。 可用于以下上下文:tcp、http 可出现在以下段中:defaults \| frontend \| listen \| backend yes \| yes \| yes \| no 该指令指定用于记录与错误、超时、重试、重分派或 HTTP 状态码 5xx 相关信息的日志格式字符串。该格式将简要用于所有受“log-separate-errors”选项影响的日志行,包括 [第 8.2.5 节](/zh/docs/haproxy/configuration-logging/#section-8-2-5)中描述的连接错误。 若该指令在 defaults 段中使用,则后续所有前端均将采用相同的日志格式。请参见 [section 8.2.6](/zh/docs/haproxy/configuration-logging/#section-8-2-6),其中详细介绍了自定义日志格式字符串。 "error-log-format" 指令会覆盖之前的 "error-log-format" 指令。 **`force-persist { if | unless } `** ```haproxy force-persist { if | unless } ``` 声明一个条件,以强制对已关闭的服务器保持持久性 可用于以下上下文:tcp、http 可出现在以下段中:defaults \| frontend \| listen \| backend 默认情况下,请求不会被分派至处于关闭状态的服务器。可以使用“option persist”强制分派,但该选项无条件生效,若设置了“option redispatch”,则会在有可用服务器时进行重分派。这使得强制某些请求到达因维护操作而被人为标记为关闭的服务器变得几乎不可能。 force-persist 语句 "force-persist" 语句允许声明多种基于 ACL 的条件,当这些条件满足时,请求将忽略服务器的宕机状态,仍尝试与其建立连接。这使得可以在服务器启动后,仍对健康检查返回错误,同时使用经过特殊配置的浏览器来测试服务。其中一种便捷的方法是使用特定的源 IP 地址,或特定的 Cookie。Cookie 的优势在于,可通过测试页面轻松地在浏览器中添加或移除。服务验证完成后,即可通过向健康检查返回有效响应,将服务对公众开放。 当满足 "if" 条件时,强制持久化功能被启用,或在满足 "unless" 条件时被禁用。使用此功能时,最终的重分派始终被禁用。 另请参阅:“option redispatch”、“ignore-persist”、“persist”以及[第 7 节](/zh/docs/haproxy/acls-and-samples/)中关于 ACL 使用的说明。 **`external-check command `** ```haproxy external-check command ``` 执行外部检查时运行的可执行文件 可用于以下上下文:tcp、http、log 可出现在以下段中:defaults \| frontend \| listen \| backend yes \| no \| yes \| yes 参数: ```text is the external command to run ``` 传递给命令的参数如下: `` `` `` `` `` 和 `` 由首个 IPv4、IPv6 或 Unix 套接字类型的监听器推导得出。若监听器为 Unix 套接字,则代理地址(proxy_address)为套接字路径,`` 的值为字符串 "NOT_USED"。在后端段中,无法确定监听器,因此 `` 和 `` 的值均为字符串 "NOT_USED"。 部分值也可通过环境变量提供。 环境变量: ```text HAPROXY_PROXY_ADDR The first bind address if available (or empty if not applicable, for example in a "backend" section). HAPROXY_PROXY_ID The backend id. HAPROXY_PROXY_NAME The backend name. HAPROXY_PROXY_PORT The first bind port if available (or empty if not applicable, for example in a "backend" section or for a UNIX socket). HAPROXY_SERVER_ADDR The server address. HAPROXY_SERVER_CURCONN The current number of connections on the server. HAPROXY_SERVER_ID The server id. HAPROXY_SERVER_MAXCONN The server max connections. HAPROXY_SERVER_NAME The server name. HAPROXY_SERVER_PORT The server port if available (or empty for a UNIX socket). HAPROXY_SERVER_SSL "0" when SSL is not used, "1" when it is used HAPROXY_SERVER_PROTO The protocol used by this server, which can be one of "cli" (the haproxy CLI), "syslog" (syslog TCP server), "peers" (peers TCP server), "h1" (HTTP/1.x server), "h2" (HTTP/2 server), or "tcp" (any other TCP server). PATH The PATH environment variable used when executing the command may be set using "external-check path". ``` 如果执行的命令退出状态为零,则认为检查通过;否则认为检查失败。 示例: ```text external-check command /bin/true ``` 另请参阅: "external-check"、"option external-check"、"external-check path" **`external-check path `** ```haproxy external-check path ``` 运行外部检查时所使用的 PATH 环境变量的值 可用于以下上下文:tcp、http、log 可出现在以下段中:defaults \| frontend \| listen \| backend yes \| no \| yes \| yes 参数: ```text is the path used when executing external command to run ``` 默认路径为空字符串。 示例: ```text external-check path "/usr/bin:/bin" ``` 另请参阅:"external-check"、"option external-check"、"external-check command" **`force-be-switch { if | unless } `** ```haproxy force-be-switch { if | unless } ``` 允许内容切换选择已禁用或未发布的后端实例。此规则可供管理员在将服务对外暴露前,用于测试流量。 可用于以下上下文:tcp、http 可出现在以下段中:defaults \| frontend \| listen \| backend 否 \| 是 \| 是 \| 否 另请参见: "disabled" **`filter [param*]`** ```haproxy filter [param*] ``` 在附加到代理的过滤器列表中添加过滤器 ``。 可用于以下上下文:tcp、http 可出现在以下段中:defaults \| frontend \| listen \| backend 否 \| 是 \| 是 \| 是 参数: ```text is the name of the filter. Officially supported filters are referenced in section 9. is a list of parameters accepted by the filter . The parsing of these parameters are the responsibility of the filter. Please refer to the documentation of the corresponding filter (section 9) for all details on the supported parameters. ``` 同一代理可多次使用过滤器行。如需,同一过滤器可被多次引用。 示例: ```text listen bind *:80 filter trace name BEFORE-HTTP-COMP filter compression filter trace name AFTER-HTTP-COMP compression algo gzip compression offload server srv1 192.168.0.1:80 ``` 参见:[第 9 节](/zh/docs/haproxy/filters/),"filter-sequence" 过滤器序列 { 请求 \| 响应 } `` 指定在代理上声明的过滤器的执行顺序。 可用于以下上下文:tcp、http 可出现在以下段中:defaults \| frontend \| listen \| backend 否 \| 是 \| 是 \| 是 以逗号分隔的过滤器名称列表(``),用于指定在代理上声明的过滤器在请求路径或响应路径上应按何种顺序执行。 当未为特定路径(即请求或响应)指定 filter-sequence 时,将使用代理上声明过滤器的顺序。 如果过滤器序列省略了代理上声明的某些过滤器,这些过滤器将不会被执行。 这是一种临时禁用过滤器的有效方式,无需将其从配置中移除。 示例: ```text global lua-load my-filter.lua # defines custom "lua.my-filter" frontend myfront filter comp-req filter comp-res filter lua.my-filter filter-sequence request lua.my-filter,comp-req filter-sequence response lua.my-filter,comp-res ``` 另请参见:"过滤器" **`fullconn `** ```haproxy fullconn ``` 指定后端负载达到多少时,服务器将达到最大连接数 可用于以下上下文:tcp、http 可出现在以下段中:defaults \| frontend \| listen \| backend yes \| no \| yes \| yes 参数: ```text is the number of connections on the backend which will make the servers use the maximal number of connections. ``` 当服务器配置了 "maxconn" 参数时,表示其并发连接数将不会超过该值。此外,若同时配置了 "minconn" 参数,则表示该限制为动态值,随后端负载变化而调整。此时,服务器将始终至少接受 `` 个连接,且不会超过 `` 个连接,当后端并发连接数低于 `` 时,该限制将在两个数值之间动态调整。这使得在正常负载下可限制服务器负载,而在重要负载时可适度提升负载能力,同时在异常负载情况下避免服务器过载。 由于很难准确设置该值,HAProxy 会自动将其设为所有可能转向此后端的前端(基于 "use_backend" 和 "default_backend" 规则)的 maxconns 之和的 10%。因此,可以安全地不显式设置该值。然而,涉及动态名称的 "use_backend" 不会被计入,因为无法判断其是否可能匹配。 示例: ```shell # The servers will accept between 100 and 1000 concurrent connections each # and the maximum of 1000 will be reached when the backend reaches 10000 # connections. backend dynamic fullconn 10000 server srv1 dyn1:80 minconn 100 maxconn 1000 server srv2 dyn2:80 minconn 100 maxconn 1000 ``` 另请参阅:“maxconn”、“server” **`guid `** ```haproxy guid ``` 为该代理指定一个区分大小写的全局唯一 ID。 可用于以下上下文:tcp、http、log 可出现在以下段中:defaults \| frontend \| listen \| backend 否 \| 是 \| 是 \| 是 `` 必须在所有 HAProxy 配置中针对每种对象类型保持唯一。格式未作限定,以允许用户自行选择命名策略。唯一限制是其长度不得超过 127 个字符。所有字母数字字符以及 '.'、':'、'-' 和 '\_' 均为有效字符。参见“shm-stats-file”。 **`hash-balance-factor `** ```haproxy hash-balance-factor ``` 指定有界负载一致性哈希的均衡因子 可用于以下上下文:tcp、http 可出现在以下段中:defaults \| frontend \| listen \| backend yes \| no \| no \| yes 参数: ```text is the control for the maximum number of concurrent requests to send to a server, expressed as a percentage of the average number of concurrent requests across all of the active servers. ``` 为使用 "hash-type consistent" 的服务器指定 "hash-balance-factor" 可启用一种算法,该算法可防止任一服务器在短时间内接收过多请求,即使某些哈希桶接收的请求远多于其他桶。将 `` 设置为 0(默认值)可禁用此功能。否则,`` 必须为大于 100 的百分比。例如,若 `` 为 150,则任一服务器的负载不得超过平均负载的 1.5 倍。若使用服务器权重,将予以尊重。 如果首选服务器被排除,算法将根据请求哈希选择另一台服务器,直至找到具有额外容量的服务器。较高的 `` 会导致服务器间负载不平衡程度增加,而较低的 `` 意味着平均需检查的服务器数量更多,从而影响性能。合理的取值范围为 125 至 200。 此设置也由“balance random”使用,后者内部依赖一致性哈希机制。 另请参见:“balance” 和 “hash-type”。 **`hash-preserve-affinity { always | maxconn | maxqueue }`** ```haproxy hash-preserve-affinity { always | maxconn | maxqueue } ``` 指定在服务器已饱和或队列已满时,使用哈希负载均衡将流分配至服务器的方法。 可以用于以下上下文:http 可出现在以下段中:defaults \| frontend \| listen \| backend yes \| no \| yes \| yes 以下值可以指定: - "always" : this is the default strategy. A stream is assigned to a server based on hashing irrespective of whether the server is currently saturated. - "maxconn" : when selected, servers that have "maxconn" set and are currently saturated will be skipped. Another server will be picked by following the hashing ring. This has no effect on servers that do not set "maxconn". If all servers are saturated, the request is enqueued to the last server in the hash ring before the initially selected server. - "maxqueue": when selected, servers that have "maxconn" set, "maxqueue" set to a non-zero value (limited queue size) and currently have a full queue will be skipped. Another server will be picked by following the hashing ring. This has no effect on servers that do not set both "maxconn" and "maxqueue". 另请参阅:"maxconn"、"maxqueue"、"hash-balance-factor" **`hash-type `** ```haproxy hash-type ``` 指定用于将哈希映射到服务器的方法 可用于以下上下文:tcp、http、log 可出现在以下段中:defaults \| frontend \| listen \| backend yes \| no \| yes \| yes 参数: ```text is the method used to select a server from the hash computed by the : map-based the hash table is a static array containing all alive servers. The hashes will be very smooth, will consider weights, but will be static in that weight changes while a server is up will be ignored. This means that there will be no slow start. Also, since a server is selected by its position in the array, most mappings are changed when the server count changes. This means that when a server goes up or down, or when a server is added to a farm, most connections will be redistributed to different servers. This can be inconvenient with caches for instance. consistent the hash table is a tree filled with many occurrences of each server. The hash key is looked up in the tree and the closest server is chosen. This hash is dynamic, it supports changing weights while the servers are up, so it is compatible with the slow start feature. It has the advantage that when a server goes up or down, only its associations are moved. When a server is added to the farm, only a few part of the mappings are redistributed, making it an ideal method for caches. However, due to its principle, the distribution will never be very smooth and it may sometimes be necessary to adjust a server's weight or its ID to get a more balanced distribution. In order to get the same distribution on multiple load balancers, it is important that all servers have the exact same IDs. Note: consistent hash uses sdbm and avalanche if no hash function is specified. is the hash function to be used: sdbm this function was created initially for sdbm (a public-domain reimplementation of ndbm) database library. It was found to do well in scrambling bits, causing better distribution of the keys and fewer splits. It also happens to be a good general hashing function with good distribution, unless the total server weight is a multiple of 64, in which case applying the avalanche modifier may help. djb2 this function was first proposed by Dan Bernstein many years ago on comp.lang.c. Studies have shown that for certain workload this function provides a better distribution than sdbm. It generally works well with text-based inputs though it can perform extremely poorly with numeric-only input or when the total server weight is a multiple of 33, unless the avalanche modifier is also used. wt6 this function was designed for HAProxy while testing other functions in the past. It is not as smooth as the other ones, but is much less sensible to the input data set or to the number of servers. It can make sense as an alternative to sdbm+avalanche or djb2+avalanche for consistent hashing or when hashing on numeric data such as a source IP address or a visitor identifier in a URL parameter. crc32 this is the most common CRC32 implementation as used in Ethernet, gzip, PNG, etc. It is slower than the other ones but may provide a better distribution or less predictable results especially when used on strings. none don't hash the key, the key will be used as a hash, this can be useful to manually hash the key using a converter for that purpose and let haproxy use the result directly. The operation will convert the key to a string if it is not already, and parse it as an integer whose value will be used as the key. Some input key types might not be relevant here (e.g. IP addresses). indicates an optional method applied after hashing the key: avalanche This directive indicates that the result from the hash function above should not be used in its raw form but that a 4-byte full avalanche hash must be applied first. The purpose of this step is to mix the resulting bits from the previous hash in order to avoid any undesired effect when the input contains some limited values or when the number of servers is a multiple of one of the hash's components (64 for SDBM, 33 for DJB2). Enabling avalanche tends to make the result less predictable, but it's also not as smooth as when using the original function. Some testing might be needed with some workloads. This hash is one of the many proposed by Bob Jenkins. ``` 默认哈希类型为“基于映射”(map-based),适用于大多数使用场景。默认函数为“sdbm”,函数的选择应基于被哈希值的取值范围。 另请参阅:“balance”、“hash-balance-factor”、“hash-preserve-affinity”、“server” **`http-after-response [ { if | unless } ]`** ```haproxy http-after-response [ { if | unless } ] ``` 对所有第 7 层响应(服务器、应用程序/服务及内部响应)的访问控制。 可以用于以下上下文:http 可出现在以下段中:defaults \| frontend \| listen \| backend yes(!) \| yes \| yes \| yes 第 7 层处理中,`http-after-response` 语句定义了一组规则。这些规则在前端、监听或后端段中按声明顺序进行评估。由于这些规则作用于响应,因此先应用后端规则,再应用前端规则。任何规则均可选择性地跟随一个基于 ACL 的条件,此时仅当该条件为真时才进行评估。 与 http-response 规则不同,此类规则适用于所有响应,包括服务器响应以及 HAProxy 生成的所有响应。这些规则在响应分析结束时进行评估,位于数据转发阶段之前。 条件在动作执行前进行评估,且该动作仅执行一次。因此,即使某个动作改变了作为条件一部分的元素,也不会造成问题。这也意味着多个动作可以依赖同一条件,只要首个改变条件评估结果的动作执行后,其余动作便会自动隐式禁用。例如,当变量为空时,从多个来源为其赋值,即采用此机制。每个实例中对“http-after-response”语句的数量无限制。 在语法中,“http-after-response”之后的第一个关键字是规则的动作,可选地后接该动作所需的若干参数。支持的动作及其相应语法详见 [第 4.3 节](/zh/docs/haproxy/proxies/#section-4-3) “动作”(请查找标记为“HTTP Aft”的动作)。 该指令仅在命名的 defaults 段中可用,不可用于匿名段。在关联的代理段之前,将先评估 defaults 段中定义的规则。为避免歧义,在此情况下,同一 defaults 段不可同时被具备前端能力的代理和具备后端能力的代理使用。这意味着,listen 段不可使用定义了此类规则的 defaults 段。 请注意:在请求解析早期阶段产生的错误由多路复用器在较低层级处理,早于任何 HTTP 分析阶段。因此,这些错误不会触发 http-after-response 规则集的评估。 示例: ```text http-after-response set-header Strict-Transport-Security "max-age=31536000" http-after-response set-header Cache-Control "no-store,no-cache,private" http-after-response set-header Pragma "no-cache" ``` **`http-check comment `** ```haproxy http-check comment ``` 为后续的 http-check 规则定义注释,若该规则执行失败,将在日志中报告。 可用于以下上下文:tcp、http 可出现在以下段中:defaults \| frontend \| listen \| backend yes \| no \| yes \| yes 参数: ```text is the comment message to add in logs if the following http-check rule fails. ``` 仅适用于 connect、send 和 expect 规则。可用于生成用户友好的错误报告。 另请参阅:“option httpchk”、“http-check connect”、“http-check send”和“http-check expect”。 **`http-check connect [default] [port ] [addr ] [send-proxy]`** ```haproxy http-check connect [default] [port ] [addr ] [send-proxy] [via-socks4] [ssl] [sni ] [alpn ] [linger] [proto ] [comment ] ``` 打开一个新连接以执行 HTTP 健康检查 可用于以下上下文:tcp、http 可出现在以下段中:defaults \| frontend \| listen \| backend yes \| no \| yes \| yes 参数: ```text comment defines a message to report if the rule evaluation fails. default Use default options of the server line to do the health checks. The server options are used only if not redefined. port if not set, check port or server port is used. It tells HAProxy where to open the connection to. must be a valid TCP port source integer, from 1 to 65535 or an sample-fetch expression. addr defines the IP address to do the health check. send-proxy send a PROXY protocol string via-socks4 enables outgoing health checks using upstream socks4 proxy. ssl opens a ciphered connection sni specifies the SNI to use to do health checks over SSL. alpn defines which protocols to advertise with ALPN. The protocol list consists in a comma-delimited list of protocol names, for instance: "h2,http/1.1". If it is not set, the server ALPN is used. proto forces the multiplexer's protocol to use for this connection. It must be an HTTP mux protocol and it must be usable on the backend side. The list of available protocols is reported in haproxy -vv. linger cleanly close the connection instead of using a single RST. ``` 与 tcp-check 健康检查类似,可配置用于执行 HTTP 健康检查的连接。该指令还应用于描述涉及多个请求/响应交互的场景,这些交互可能在不同端口上进行,或涉及不同的服务器。 当服务器行中未配置 TCP 端口,且未使用 server port 指令时,http-check 序列的第一步必须使用 "http-check connect" 指定端口。 在 http-check 规则集中,必须包含一个 'connect' 规则,且规则集必须以 'connect' 规则开头。此举旨在确保管理员清楚了解其操作意图。 当连接必须启动规则集时,仍可由 set-var、unset-var 或 comment 规则先行。 示例: ```shell # check HTTP and HTTPs services on a server. # first open port 80 thanks to server line port directive, then # tcp-check opens port 443, ciphered and run a request on it: option httpchk http-check connect http-check send meth GET uri / ver HTTP/1.1 hdr host haproxy.1wt.eu http-check expect status 200-399 http-check connect port 443 ssl sni haproxy.1wt.eu http-check send meth GET uri / ver HTTP/1.1 hdr host haproxy.1wt.eu http-check expect status 200-399 server www 10.0.0.1 check port 80 ``` 另请参阅:“option httpchk”、“http-check send”、“http-check expect” **`http-check disable-on-404`** ```haproxy http-check disable-on-404 ``` 在健康检查返回 HTTP/404 响应时启用维护模式 可用于以下上下文:tcp、http 可出现在以下段中:defaults \| frontend \| listen \| backend yes \| no \| yes \| yes 参数:无 当启用此选项时,返回 HTTP 状态码 404 的服务器将不再参与后续的负载均衡,但仍会接收持久连接。这为 Web 管理员提供了一种非常便捷的服务器优雅关闭方式。需要注意的是,处于此模式下检测到失败的服务器不会触发告警,仅生成通知。若服务器再次返回 2xx 或 3xx 响应,将立即被重新加入服务器池。统计信息页面中,该服务器的状态显示为“NOLB”。请注意,此选项仅在与“httpchk”选项配合使用时生效。若与“http-check expect”选项一同使用,则本选项具有更高优先级,即 404 响应仍被视为软停止。此外,已停止的服务器即使返回 404,仍将持续处于停止状态。此选项仅对运行中的服务器进行评估。 另请参见:“option httpchk” 和 “http-check expect”。 **`http-check expect [min-recv ] [comment ]`** ```haproxy http-check expect [min-recv ] [comment ] [ok-status ] [error-status ] [tout-status ] [on-success ] [on-error ] [status-code ] [!] ``` 使 HTTP 健康检查考虑响应内容或特定状态码 可用于以下上下文:tcp、http 可出现在以下段中:defaults \| frontend \| listen \| backend yes \| no \| yes \| yes 参数: ```text comment defines a message to report if the rule evaluation fails. min-recv is optional and can define the minimum amount of data required to evaluate the current expect rule. If the number of received bytes is under this limit, the check will wait for more data. This option can be used to resolve some ambiguous matching rules or to avoid executing costly regex matches on content known to be still incomplete. If an exact string is used, the minimum between the string length and this parameter is used. This parameter is ignored if it is set to -1. If the expect rule does not match, the check will wait for more data. If set to 0, the evaluation result is always conclusive. ok-status is optional and can be used to set the check status if the expect rule is successfully evaluated and if it is the last rule in the tcp-check ruleset. "L7OK", "L7OKC", "L6OK" and "L4OK" are supported: - L7OK : check passed on layer 7 - L7OKC: check conditionally passed on layer 7, set server to NOLB state. - L6OK : check passed on layer 6 - L4OK : check passed on layer 4 By default "L7OK" is used. error-status is optional and can be used to set the check status if an error occurred during the expect rule evaluation. "L7OKC", "L7RSP", "L7STS", "L6RSP" and "L4CON" are supported: - L7OKC: check conditionally passed on layer 7, set server to NOLB state. - L7RSP: layer 7 invalid response - protocol error - L7STS: layer 7 response error, for example HTTP 5xx - L6RSP: layer 6 invalid response - protocol error - L4CON: layer 1-4 connection problem By default "L7RSP" is used. tout-status is optional and can be used to set the check status if a timeout occurred during the expect rule evaluation. "L7TOUT", "L6TOUT", and "L4TOUT" are supported: - L7TOUT: layer 7 (HTTP/SMTP) timeout - L6TOUT: layer 6 (SSL) timeout - L4TOUT: layer 1-4 timeout By default "L7TOUT" is used. on-success is optional and can be used to customize the informational message reported in logs if the expect rule is successfully evaluated and if it is the last rule in the tcp-check ruleset. is a Custom log format string (see section 8.2.6). on-error is optional and can be used to customize the informational message reported in logs if an error occurred during the expect rule evaluation. is a Custom log format string (see section 8.2.6). status-code is optional and can be used to set the check status code reported in logs, on success or on error. is a standard HAProxy expression formed by a sample-fetch followed by some converters. is a keyword indicating how to look for a specific pattern in the response. The keyword may be one of "status", "rstatus", "hdr", "fhdr", "string", or "rstring". The keyword may be preceded by an exclamation mark ("!") to negate the match. Spaces are allowed between the exclamation mark and the keyword. See below for more details on the supported keywords. is the pattern to look for. It may be a string, a regular expression or a more complex pattern with several arguments. If the string pattern contains spaces, they must be escaped with the usual backslash ('\'). ``` 默认情况下,“option httpchk”认为响应状态码为 2xx 和 3xx 时有效,其余状态码为无效。当使用“http-check expect”时,它将定义何为有效或无效。一个后端中仅支持一条“http-check”语句。若服务器无响应或超时,检查显然会失败。可用的匹配项包括: ```text status : test the status codes found parsing string. it must be a comma-separated list of status codes or range codes. A health check response will be considered as valid if the response's status code matches any status code or is inside any range of the list. If the "status" keyword is prefixed with "!", then the response will be considered invalid if the status code matches. rstatus : test a regular expression for the HTTP status code. A health check response will be considered valid if the response's status code matches the expression. If the "rstatus" keyword is prefixed with "!", then the response will be considered invalid if the status code matches. This is mostly used to check for multiple codes. hdr { name | name-lf } [ -m ] [ { value | value-lf } [ -m ] : test the specified header pattern on the HTTP response headers. The name pattern is mandatory but the value pattern is optional. If not specified, only the header presence is verified. is the matching method, applied on the header name or the header value. Supported matching methods are "str" (exact match), "beg" (prefix match), "end" (suffix match), "sub" (substring match) or "reg" (regex match). If not specified, exact matching method is used. If the "name-lf" parameter is used, is evaluated as a Custom log format string (see section 8.2.6). If "value-lf" parameter is used, is evaluated as a log-format string. These parameters cannot be used with the regex matching method. Finally, the header value is considered as comma-separated list. Note that matchings are case insensitive on the header names. fhdr { name | name-lf } [ -m ] [ { value | value-lf } [ -m ] : test the specified full header pattern on the HTTP response headers. It does exactly the same as the "hdr" keyword, except the full header value is tested, commas are not considered as delimiters. string : test the exact string match in the HTTP response body. A health check response will be considered valid if the response's body contains this exact string. If the "string" keyword is prefixed with "!", then the response will be considered invalid if the body contains this string. This can be used to look for a mandatory word at the end of a dynamic page, or to detect a failure when a specific error appears on the check page (e.g. a stack trace). rstring : test a regular expression on the HTTP response body. A health check response will be considered valid if the response's body matches this expression. If the "rstring" keyword is prefixed with "!", then the response will be considered invalid if the body matches the expression. This can be used to look for a mandatory word at the end of a dynamic page, or to detect a failure when a specific error appears on the check page (e.g. a stack trace). string-lf : test a Custom log format string (see section 8.2.6) match in the HTTP response body. A health check response will be considered valid if the response's body contains the string resulting of the evaluation of , which follows the log-format rules. If prefixed with "!", then the response will be considered invalid if the body contains the string. ``` 请注意,响应大小将受到全局 "tune.bufsize" 选项的限制,该选项默认值为 16384 字节。因此,使用 "string" 或 "rstring" 时,过大的响应可能不包含必需的模式。若确实需要处理大响应,可通过设置全局变量更改默认最大大小。但需注意,解析非常大的响应可能会浪费部分 CPU 周期,尤其是在使用正则表达式时,且始终建议将检查聚焦于较小的资源。 在 http-check 规则集中,最后一个 expect 规则可以是隐式的。如果在最后一个 "http-check send" 之后未指定 expect 规则,则会定义一个隐式的 expect 规则,用于匹配 2xx 或 3xx 状态码。这意味着,即使完全未设置 "http-check" 规则,仅设置了 "option httpchk" 时,该规则同样会被定义。 最后,如果将“http-check expect”与“http-check disable-on-404”结合使用,则当服务器响应 404 时,后者具有优先权。 示例: ```shell # only accept status 200 as valid http-check expect status 200,201,300-310 # be sure a sessid coookie is set http-check expect hdr name "set-cookie" value -m beg "sessid=" # consider SQL errors as errors http-check expect ! string SQL\ Error # consider status 5xx only as errors http-check expect ! rstatus ^5 # check that we have a correct hexadecimal tag before /html http-check expect rstring ``` 另请参阅:“option httpchk”、“http-check connect”、“http-check disable-on-404”和“http-check send”。 **`http-check send [meth ] [{ uri | uri-lf }>] [ver ]`** ```haproxy http-check send [meth ] [{ uri | uri-lf }>] [ver ] [hdr ]* [{ body | body-lf }] [comment ] ``` 在 HTTP 健康检查发送的请求中添加可能的头字段列表和/或请求体。 可用于以下上下文:tcp、http 可出现在以下段中:defaults \| frontend \| listen \| backend yes \| no \| yes \| yes 参数: ```text comment defines a message to report if the rule evaluation fails. meth is the optional HTTP method used with the requests. When not set, the "OPTIONS" method is used, as it generally requires low server processing and is easy to filter out from the logs. Any method may be used, though it is not recommended to invent non-standard ones. uri is optional and set the URI referenced in the HTTP requests to the string . It defaults to "/" which is accessible by default on almost any server, but may be changed to any other URI. Query strings are permitted. uri-lf is optional and set the URI referenced in the HTTP requests using the Custom log format (see section 8.2.6). It defaults to "/" which is accessible by default on almost any server, but may be changed to any other URI. Query strings are permitted. ver is the optional HTTP version string. It defaults to "HTTP/1.0" but some servers might behave incorrectly in HTTP 1.0, so turning it to HTTP/1.1 may sometimes help. Note that the Host field is mandatory in HTTP/1.1, use "hdr" argument to add it. hdr adds the HTTP header field whose name is specified in and whose value is defined by , which follows the Custom log format rules described in section 8.2.6. body add the body defined by to the request sent during HTTP health checks. If defined, the "Content-Length" header is thus automatically added to the request. body-lf add the body defined by the Custom log format (see section 8.2.6) to the request sent during HTTP health checks. If defined, the "Content-Length" header is thus automatically added to the request. ``` 除了由 "option httpchk" 指令定义的请求行外,以下方式是向 HTTP 健康检查请求中添加头字段并可选地添加请求体的正确方法。若定义了请求体,则会自动添加相应的 "Content-Length" 头字段。因此,在 "http-check send" 提供的请求中,不应包含该头字段或 "Transfer-encoding" 头字段,否则将被忽略。在 "option httpchk" 行中版本字符串后添加头字段的旧方法现已弃用。 此外,“http-check send” 不支持 HTTP 持久连接。请注意,除非通过 hdr 条目已配置 Connection 头,否则它会自动附加一个 "Connection: close" 头。 请注意,当 Host 头和请求授权信息均被定义时,二者会自动同步。这意味着在发送 HTTP 请求时,若在请求中插入 Host 头,则请求授权信息会相应更新。因此,若发现 Host 头值覆盖了配置的请求授权信息,无需感到意外。 请注意,目前在 HTTP/1.1 及以上版本的请求中,不会自动添加 Host 头。应显式添加。 另请参见:“option httpchk”、“http-check send-state”和“http-check expect”。 **`http-check send-state`** ```haproxy http-check send-state ``` 启用 HTTP 健康检查时发送状态头 可用于以下上下文:tcp、http 可出现在以下段中:defaults \| frontend \| listen \| backend yes \| no \| yes \| yes 参数:无 当启用此选项时,HAProxy 会始终向每个服务器发送一个特殊头字段 "X-Haproxy-Server-State",其中包含一组参数,用于指示 HAProxy 对各服务器的当前状态判断。例如,当服务器在未访问 HAProxy 的情况下被操作时,管理员可借此确认 HAProxy 是否仍认为该服务器处于运行状态,或该服务器是否为某服务器组中的最后一个成员。 头由分号分隔的字段组成,第一个字段为一个单词("UP"、"DOWN"、"NOLB"),后接在状态转换前有效的检查次数,格式与统计信息界面中显示的一致。后续字段格式为 "``=``",以任意顺序表示统计信息界面中可用的某些值:- 变量 "address",包含后端服务器的地址。该值对应服务器声明中的 `
` 字段。对于 Unix 域套接字,其值为 "unix"。 - a variable "port", containing the port of the backend server. This corresponds to the `` field in the server declaration. For unix domain sockets, it will read "unix". - a variable "name", containing the name of the backend followed by a slash ("/") then the name of the server. This can be used when a server is checked in multiple backends. - a variable "node" containing the name of the HAProxy node, as set in the global "node" variable, otherwise the system's hostname if unspecified. - a variable "weight" indicating the weight of the server, a slash ("/") and the total weight of the farm (just counting usable servers). This helps to know if other servers are available to handle the load when this one fails. - a variable "scur" indicating the current number of concurrent connections on the server, followed by a slash ("/") then the total number of connections on all servers of the same backend. - a variable "qcur" indicating the current number of requests in the server's queue. 应用服务器接收到的头示例: ```shell >>> X-Haproxy-Server-State: UP 2/3; name=bck/srv2; node=lb1; weight=1/2; \ scur=13/22; qcur=0 ``` 另请参阅:“option httpchk”、“http-check disable-on-404” 和 “http-check send”。 **`http-check set-var([,...]) `** ```haproxy http-check set-var([,...]) http-check set-var-fmt([,...]) ``` 此操作用于设置变量的内容。变量在行内声明。 可用于以下上下文:tcp、http 可出现在以下段中:defaults \| frontend \| listen \| backend yes \| no \| yes \| yes 参数: ```text The name of the variable. Only "proc", "sess" and "check" scopes can be used. See section 2.8 about variables for details. A set of conditions that must all be true for the variable to actually be set (such as "ifnotempty", "ifgt" ...). See the set-var converter's description for a full list of possible conditions. Is a sample-fetch expression potentially followed by converters. This is the value expressed using Custom log format (see Custom Log Format in section 8.2.6). ``` 示例: ```text http-check set-var(check.port) int(1234) http-check set-var-fmt(check.port) "name=%H" ``` **`http-check unset-var()`** ```haproxy http-check unset-var() ``` 释放变量在其作用域内的引用。 可用于以下上下文:tcp、http 可出现在以下段中:defaults \| frontend \| listen \| backend yes \| no \| yes \| yes 参数: ```text The name of the variable. Only "proc", "sess" and "check" scopes can be used. See section 2.8 about variables for details. ``` 示例: ```text http-check unset-var(check.port) ``` **`http-error status [content-type ]`** ```haproxy http-error status [content-type ] [ { default-errorfiles | errorfile | errorfiles | ``` file `` | lf-file `` | string `` | lf-string `` } ] [ hdr `` `` ]* 定义自定义错误消息,用于替代 HAProxy 生成的错误信息。 可以用于以下上下文:http 可出现在以下段中:defaults \| frontend \| listen \| backend yes \| yes \| yes \| yes 参数: ```text status is the HTTP status code. It must be specified. Currently, HAProxy is capable of generating codes 200, 400, 401, 403, 404, 405, 407, 408, 410, 413, 414, 425, 429, 431, 500, 501, 502, 503, and 504. content-type is the response content type, for instance "text/plain". This parameter is ignored and should be omitted when an errorfile is configured or when the payload is empty. Otherwise, it must be defined. default-errorfiles Reset the previously defined error message for current proxy for the status . If used on a backend, the frontend error message is used, if defined. If used on a frontend, the default error message is used. errorfile designates a file containing the full HTTP response. It is recommended to follow the common practice of appending ".http" to the filename so that people do not confuse the response with HTML error pages, and to use absolute paths, since files are read before any chroot is performed. errorfiles designates the http-errors section to use to import the error message with the status code . If no such message is found, the proxy's error messages are considered. file specifies the file to use as response payload. If the file is not empty, its content-type must be set as argument to "content-type", otherwise, any "content-type" argument is ignored. is considered as a raw string. string specifies the raw string to use as response payload. The content-type must always be set as argument to "content-type". lf-file specifies the file to use as response payload. If the file is not empty, its content-type must be set as argument to "content-type", otherwise, any "content-type" argument is ignored. is evaluated as a Custom log format (see section 8.2.6). lf-string specifies the log-format string to use as response payload. The content-type must always be set as argument to "content-type". hdr adds to the response the HTTP header field whose name is specified in and whose value is defined by , which follows the Custom log format rules (see section 8.2.6). This parameter is ignored if an errorfile is used. ``` 此指令可用于替代 "errorfile",以定义自定义错误消息。与 "errorfile" 指令相同,它用于处理 HAProxy 检测并返回的错误。若定义了 errorfile,则 HAProxy 启动时会对其进行解析,且必须符合 HTTP 标准。生成的响应不得超过配置的缓冲区大小(BUFFSIZE),否则将返回内部错误。最后,若考虑使用某些 http-after-response 规则来重写这些错误,应确保预留的缓冲区空间可用(参见 "tune.maxrewrite")。 配置文件与之同时读取并保留在内存中。因此,即使进程已执行 chroot,错误仍会持续返回,且在进程运行期间不会考虑任何文件变更。 请注意:在请求解析早期阶段产生的 400/408/500 错误由多路复用器在较低层级处理。此层级不支持自定义格式化。因此,仅支持使用 "errorfile" 指令定义的静态错误消息。然而,此限制仅存在于请求头解析期间或两次事务之间。 参见:“errorfile”、“errorfiles”、“errorloc”、“errorloc302”、“errorloc303”以及 [第 12.4 节](/zh/docs/haproxy/other-sections/#section-12-4) 关于 http-errors 的内容。 **`http-request [options...] [ { if | unless } ]`** ```haproxy http-request [options...] [ { if | unless } ] ``` 第 7 层请求的访问控制 可以用于以下上下文:http 可出现在以下段中:defaults \| frontend \| listen \| backend yes(!) \| yes \| yes \| yes 第 7 层处理中,`http-request` 语句用于定义一组规则。这些规则在前端、监听或后端段中按声明顺序进行评估。每条规则可选择性地跟随一个基于 ACL 的条件,此时仅当该条件求值为真时,规则才会被评估。 条件在动作执行前进行评估,且该动作仅执行一次。因此,即使某个动作改变了作为条件一部分的元素,也不会造成问题。这也意味着多个动作可以依赖同一条件,只要首个改变条件评估结果的动作执行后,其余动作便会自动隐式禁用。例如,当变量为空时,从多个来源为其赋值,即采用此机制。每个实例中“http-request”语句的数量无限制。 在 "http-request" 语法中,首个关键字为规则的动作,可选地后接该动作所需的若干参数。支持的动作及其对应语法详见 [第 4.3 节](/zh/docs/haproxy/proxies/#section-4-3) “动作”(请查找标记为“HTTP Req”的动作)。 该指令仅在命名的 defaults 段中可用,不可用于匿名段。在关联的代理段之前,将先评估 defaults 段中定义的规则。为避免歧义,在此情况下,同一 defaults 段不可同时被具备前端能力的代理和具备后端能力的代理使用。这意味着,listen 段不可使用定义了此类规则的 defaults 段。 示例: ```text 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 ``` 示例: ```text acl key req.hdr(X-Add-Acl-Key) -m found acl add path /addacl acl del path /delacl acl myhost hdr(Host) -f myhost.lst http-request add-acl(myhost.lst) %[req.hdr(X-Add-Acl-Key)] if key add http-request del-acl(myhost.lst) %[req.hdr(X-Add-Acl-Key)] if key del ``` 示例: ```text acl value req.hdr(X-Value) -m found acl setmap path /setmap acl delmap path /delmap use_backend bk_appli if { hdr(Host),map_str(map.lst) -m found } http-request set-map(map.lst) %[src] %[req.hdr(X-Value)] if setmap value http-request del-map(map.lst) %[src] if delmap ``` 另请参阅:“stats http-request”,[第 12.2 节](/zh/docs/haproxy/other-sections/#section-12-2) 关于 userlists 的说明,以及 [第 7 节](/zh/docs/haproxy/acls-and-samples/) 关于 ACL 使用的说明。 **`http-response [ { if | unless } ]`** ```haproxy http-response [ { if | unless } ] ``` 第 7 层响应的访问控制 可以用于以下上下文:http 可出现在以下段中:defaults \| frontend \| listen \| backend yes(!) \| yes \| yes \| yes 第 7 层处理中,`http-response` 语句定义了一组规则。这些规则在前端、监听或后端段中按声明顺序进行评估。由于这些规则作用于响应,因此先应用后端规则,再应用前端规则。任何规则均可选择性地跟随一个基于 ACL 的条件,此时仅当该条件求值为真时才进行评估。 条件在动作执行前进行评估,且该动作仅执行一次。因此,即使某个动作改变了作为条件一部分的元素,也不会造成问题。这也意味着多个动作可以依赖同一条件,只要首个改变条件评估结果的动作执行后,其余动作便会自动隐式禁用。例如,当变量为空时,从多个来源为其赋值,即采用此机制。每个实例中“http-response”语句的数量无限制。 在语法中,“http-response”之后的第一个关键字是规则的动作,可选地后接该动作所需的若干参数。支持的动作及其各自语法详见 [第 4.3 节](/zh/docs/haproxy/proxies/#section-4-3)“动作”(请查找标记为“HTTP 响应”的动作)。 该指令仅在命名的 defaults 段中可用,不可用于匿名段。在关联的代理段之前,将先评估 defaults 段中定义的规则。为避免歧义,在此情况下,同一 defaults 段不可同时被具备前端能力的代理和具备后端能力的代理使用。这意味着,listen 段不可使用定义了此类规则的 defaults 段。 示例: ```text acl key_acl res.hdr(X-Acl-Key) -m found acl myhost hdr(Host) -f myhost.lst http-response add-acl(myhost.lst) %[res.hdr(X-Acl-Key)] if key_acl http-response del-acl(myhost.lst) %[res.hdr(X-Acl-Key)] if key_acl ``` 示例: ```text acl value res.hdr(X-Value) -m found use_backend bk_appli if { hdr(Host),map_str(map.lst) -m found } http-response set-map(map.lst) %[src] %[res.hdr(X-Value)] if value http-response del-map(map.lst) %[src] if ! value ``` 另请参阅:“http-request”,[第 12.2 节](/zh/docs/haproxy/other-sections/#section-12-2) 关于 userlists 的说明以及 [第 7 节](/zh/docs/haproxy/acls-and-samples/) 关于 ACL 使用的说明。 **`http-reuse { never | safe | aggressive | always }`** ```haproxy http-reuse { never | safe | aggressive | always } ``` 声明空闲 HTTP 连接在请求之间如何共享 可以用于以下上下文:http 可出现在以下段中:defaults \| frontend \| listen \| backend yes \| no \| yes \| yes 为避免为每个 HTTP 请求建立与后端服务器的新连接所带来的开销,HAProxy 会在使用后尽量保持这些空闲连接处于打开状态。这些连接与特定服务器相关,并存储在一个称为连接池的列表中,且根据一组共同的关键属性进行分组。后续的 HTTP 请求将触发对关联连接池中具有相同属性的兼容连接的查找,从而复用该连接,而非建立新的连接。 可通过服务器关键字 "pool-max-conn" 指定服务器上保持的空闲连接数量上限。未使用的连接将根据 "pool-purge-delay" 间隔周期性地清除。 以下连接属性用于确定空闲连接在特定请求上是否可重用: - 源地址和目标地址 - PROXY 协议 - TOS 和 mark 套接字选项 - 连接名称,由 "pool-conn-name" 表达式求值结果确定,若该表达式不存在,则由 "sni" 表达式确定,其默认值为 "req.hdr(host),field(1,:)",即使用入站请求的 "Host" 头字段,不包含冒号和端口号。 在某些情况下,由于额外的限制,不会执行连接查找或复用。这由通过关键字参数指定的复用策略决定: - "never" : idle connections are never shared between sessions. This mode may be enforced to cancel a different strategy inherited from a defaults section or for troubleshooting. For example, if an old bogus application considers that multiple requests over the same connection come from the same client and it is not possible to fix the application, it may be desirable to disable connection sharing in a single backend. An example of such an application could be an old HAProxy using cookie insertion in tunnel mode and not checking any request past the first one. - "safe" : this is the default and the recommended strategy. The first request of a session is always sent over its own connection, and only subsequent requests may be dispatched over other existing connections. This ensures that in case the server closes the connection when the request is being sent, the browser can decide to silently retry it. Since it is exactly equivalent to regular keep-alive, there should be no side effects. There is also a special handling for the connections using protocols subject to Head-of-line blocking (backend with h2 or fcgi). In this case, when at least one stream is processed, the used connection is reserved to handle streams of the same session. When no more streams are processed, the connection is released and can be reused. - "aggressive": this mode may be useful in webservices environments where all servers are not necessarily known and where it would be appreciable to deliver most first requests over existing connections. In this case, first requests are only delivered over existing connections that have been reused at least once, proving that the server correctly supports connection reuse. It should only be used when it's sure that the client can retry a failed request once in a while and where the benefit of aggressive connection reuse significantly outweighs the downsides of rare connection failures. - "always": this mode is only recommended when the path to the server is known for never breaking existing connections quickly after releasing them. It allows the first request of a session to be sent to an existing connection. This can provide a significant performance increase over the "safe" strategy when the backend is a cache farm, since such components tend to show a consistent behavior and will benefit from the connection sharing. It is recommended that the "http-keep-alive" timeout remains low in this mode so that no dead connections remain usable. In most cases, this will lead to the same performance gains as "aggressive" but with more risks. It should only be used when it improves the situation over "aggressive". 请注意,使用某些依赖连接的伪造认证机制(如 NTLM)的连接,若可能将被标记为私有,且永不共享。然而,当使用具备多路复用能力的协议,并启用大于默认“安全”策略的重用模式级别时,情况将不同,此时无法阻止连接已被共享。 决定在处理完成后是否保持空闲连接打开或关闭的规则,同样由 "tune.pool-low-fd-ratio"(默认值:20%)和 "tune.pool-high-fd-ratio"(默认值:25%)控制。这两个参数分别对应于空闲连接所占用的总文件描述符比例阈值,当超过该阈值时,HAProxy 将分别停止在响应后保持连接打开,或主动终止空闲连接。某些配置中空闲连接比例极高,可能是由于全局 "maxconn" 值过低,或前端存在大量 HTTP/2 或 HTTP/3 流量(连接数少),而后端使用 HTTP/1 连接,可能导致连接复用率下降,因为保持打开的连接过少。在此情况下,调整这些阈值或简单地提高全局 "maxconn" 值可能是有益的。 在某些罕见情况下,当主机名用于区分出站 TLS 连接(例如正向代理)且大多数请求的目标主机不同时,连接复用率会非常低。此时,在连接有机会被复用之前,系统可能已触发对使用频率较低连接的自动淘汰机制。这是因为该机制会持续测量维持服务所需的平均连接数,以避免资源耗尽。在此类场景中,将“pool-low-conn”设置为接近预期空闲连接平均数的值,有助于通过鼓励线程建立自己的连接,而非尝试选取其他线程的连接,从而减少可用连接池的收缩,保留更多连接。 如果本地托管的服务器使用单个证书(包含多个主机名或通配符)并运行多个站点,建议在“server”行上使用“no-sni-auto”而非保留对单一主机名的连接,以提升连接复用率。部分服务器可能在主机名与 SNI 之间执行过多检查,导致拒绝后续请求,因此该选项需预先验证。默认行为(“sni-auto”)旨在确保与此类服务器的兼容性,更为安全。 当显式启用线程组时,需注意空闲连接仅可在同一组内的线程之间复用。因此,组间负载不均可能导致需要更多空闲连接,从而降低复用率。可采用相同解决方案(增加全局 "maxconn" 值或提高池比例)。 参见: "option http-keep-alive"、"pool-conn-name"、"pool-max-conn"、"pool-purge-delay"、"server maxconn"、"sni"、"thread-groups"、"tune.pool-high-fd-ratio"、"tune.pool-low-fd-ratio" **`http-send-name-header [
]`** ```haproxy http-send-name-header [
] ``` 将服务器名称添加到请求中。使用由 `
` 提供的头字符串 可以用于以下上下文:http 可出现在以下段中:defaults \| frontend \| listen \| backend yes \| no \| yes \| yes 参数: ```text
The header string to use to send the server name ``` “http-send-name-header” 语句会导致名为 `
` 的头字段在请求即将通过网络发送时被设置为目标服务器的名称。该头字段中任何已存在的实例均会被移除。在重试和重分派过程中,该头字段会更新,始终反映当前尝试连接的服务器。由于该头字段在连接建立过程的后期才被修改,可能对已修改的其他头字段产生意外影响。例如,与传输层头(如 connection、content-length、transfer-encoding 等)一起使用时,很可能导致向服务器发送无效请求。因此,以下头字段被禁止使用:host、content-length、transfer-encoding 和 connection。 另请参见:服务器 **`id `** ```haproxy id ``` 为代理设置持久化 ID。 可用于以下上下文:tcp、http、log 可出现在以下段中:defaults \| frontend \| listen \| backend 否 \| 是 \| 是 \| 是 参数:无 为代理设置一个持久化 ID。该 ID 必须唯一且为正数。若未设置,将自动分配一个未使用的 ID。由于历史行为,除非显式设置,否则值 1 不会被使用。因此,自动分配的最小值为 2。该 ID 当前仅在统计信息中返回。 **`ignore-persist { if | unless } `** ```haproxy ignore-persist { if | unless } ``` 声明一个条件以忽略持久性 可用于以下上下文:tcp、http 可出现在以下段中:defaults \| frontend \| listen \| backend 默认情况下,启用 cookie 持久性后,所有包含该 cookie 的请求将无条件保持持久性(前提是目标服务器处于运行状态)。 本节中的 "ignore-persist" 语句允许声明多种基于 ACL 的条件,当这些条件满足时,将导致请求忽略持久性。这在对静态文件请求进行负载均衡时有时很有用,因为这类请求通常不需要持久性。该功能也可用于针对特定 User-Agent 完全禁用持久性(例如,某些网络爬虫机器人)。 当满足 "if" 条件时,持久性将被忽略,或除非满足 "unless" 条件。 示例: ```text acl url_static path_beg /static /images /img /css acl url_static path_end .gif .png .jpg .css .js ignore-persist if url_static ``` 另请参阅:“force-persist”、“cookie”以及 [第 7 节](/zh/docs/haproxy/acls-and-samples/) 中关于 ACL 使用的说明。 **`load-server-state-from-file { global | local | none }`** ```haproxy load-server-state-from-file { global | local | none } ``` 允许 HAProxy 无缝重载 可用于以下上下文:tcp、http、log 可出现在以下段中:defaults \| frontend \| listen \| backend yes \| no \| yes \| yes 本指令用于指定 HAProxy 从何处加载前一次运行进程保存的服务器状态文件。这样,在启动过程中、处理流量之前,新进程可以将旧状态精确地应用到服务器上,如同未发生重载一般。`load-server-state-from-file` 指令的作用是告知 HAProxy 使用哪个文件。目前,该指令仅支持两个参数:一个用于禁止加载状态,另一个用于从包含所有后端和服务器状态的文件中加载状态。状态文件可通过在统计信息套接字上执行命令 `show servers state` 并重定向输出生成。 文件格式已版本化,且非常具体。如需理解,请阅读“show servers state”命令的文档(管理指南第 9.3 章)。 参数: ```text global load the content of the file pointed by the global directive named "server-state-file". local load the content of the file pointed by the directive "server-state-file-name" if set. If not set, then the backend name is used as a file name. none don't load any stat for this backend ``` 注意:默认情况下,服务器的 IP 地址在重载过程中得以保留,但可通过服务器的 "init-addr" 设置更改其顺序。这意味着通过 CLI 在运行时执行的 IP 地址变更将被保留,且若启用了状态文件,对本地解析器(例如 /etc/hosts)的任何更改可能不会产生效果。 - server's weight is applied from previous running process unless it has has changed between previous and new configuration files. 示例:最小配置 global stats socket /tmp/socket server-state-file /tmp/server_state defaults load-server-state-from-file global backend bk server s1 127.0.0.1:22 check weight 11 server s2 127.0.0.1:22 check weight 12 然后可以运行: ```text socat /tmp/socket - <<< "show servers state" > /tmp/server_state ``` /tmp/server_state 文件的内容应如下所示: ```shell 1 # 1 bk 1 s1 127.0.0.1 2 0 11 11 4 6 3 4 6 0 0 1 bk 2 s2 127.0.0.1 2 0 12 12 4 6 3 4 6 0 0 ``` 示例:最小配置 global stats socket /tmp/socket server-state-base /etc/haproxy/states defaults load-server-state-from-file local backend bk server s1 127.0.0.1:22 check weight 11 server s2 127.0.0.1:22 check weight 12 然后可以运行: ```text socat /tmp/socket - <<< "show servers state bk" > /etc/haproxy/states/bk ``` /etc/haproxy/states/bk 文件内容如下: ```shell 1 # 1 bk 1 s1 127.0.0.1 2 0 11 11 4 6 3 4 6 0 0 1 bk 2 s2 127.0.0.1 2 0 12 12 4 6 3 4 6 0 0 ``` 另请参见:“server-state-file”、“server-state-file-name”和“show servers state” **`log global`** ```haproxy log global log [len ] [format ] [sample :] [profile ] [ []] no log ``` 启用每个实例的事件和流量日志记录。 可用于以下上下文:tcp、http、log 可出现在以下段中:defaults \| frontend \| listen \| backend yes \| yes \| yes \| yes 前缀: ```text no should be used when the logger list must be flushed. For example, if you don't want to inherit from the default logger list. This prefix does not allow arguments. ``` 参数: ```text global should be used when the instance's logging parameters are the same as the global ones. This is the most common usage. "global" replaces all log arguments with those of the log entries found in the "global" section. Only one "log global" statement may be used per instance, and this form takes no other parameter. indicates where to send the logs. It takes the same format as for the "global" section's logs, and can be one of: - An IPv4 address optionally followed by a colon (':') and a UDP port. If no port is specified, 514 is used by default (the standard syslog port). - An IPv6 address followed by a colon (':') and optionally a UDP port. If no port is specified, 514 is used by default (the standard syslog port). - A filesystem path to a UNIX domain socket, keeping in mind considerations for chroot (be sure the path is accessible inside the chroot) and uid/gid (be sure the path is appropriately writable). - A file descriptor number in the form "fd@", which may point to a pipe, terminal, or socket. In this case unbuffered logs are used and one writev() call per log is performed. This is a bit expensive but acceptable for most workloads. Messages sent this way will not be truncated but may be dropped, in which case the DroppedLogs counter will be incremented. The writev() call is atomic even on pipes for messages up to PIPE_BUF size, which POSIX recommends to be at least 512 and which is 4096 bytes on most modern operating systems. Any larger message may be interleaved with messages from other processes. Exceptionally for debugging purposes the file descriptor may also be directed to a file, but doing so will significantly slow HAProxy down as non-blocking calls will be ignored. Also there will be no way to purge nor rotate this file without restarting the process. Note that the configured syslog format is preserved, so the output is suitable for use with a TCP syslog server. See also the "short" and "raw" formats below. - "stdout" / "stderr", which are respectively aliases for "fd@1" and "fd@2", see above. - A ring buffer in the form "ring@", which will correspond to an in-memory ring buffer accessible over the CLI using the "show events" command, which will also list existing rings and their sizes. Such buffers are lost on reload or restart but when used as a complement this can help troubleshooting by having the logs instantly available. See section 12.5 about rings. - A log backend in the form "backend@", which will send log messages to the corresponding log backend responsible for sending the message to the proper server according to the backend's lb settings. A log backend is a backend section with "mode log" set (see "mode" for more information). - An explicit stream address prefix such as "tcp@","tcp6@", "tcp4@" or "uxst@" will allocate an implicit ring buffer with a stream forward server targeting the given address. You may want to reference some environment variables in the address parameter, see section 2.3 about environment variables. is an optional maximum line length. Log lines larger than this value will be truncated before being sent. The reason is that syslog servers act differently on log line length. All servers support the default value of 1024, but some servers simply drop larger lines while others do log them. If a server supports long lines, it may make sense to set this value here in order to avoid truncating long lines. Similarly, if a server drops long lines, it is preferable to truncate them before sending them. Accepted values are 80 to 65535 inclusive. The default value of 1024 is generally fine for all standard usages. Some specific cases of long captures or JSON-formatted logs may require larger values. You may also need to increase "tune.http.logurilen" if your request URIs are truncated. A list of comma-separated ranges to identify the logs to sample. This is used to balance the load of the logs to send to the log server. The limits of the ranges cannot be null. They are numbered from 1. The size or period (in number of logs) of the sample must be set with parameter. The size of the sample in number of logs to consider when balancing their logging loads. It is used to balance the load of the logs to send to the syslog server. This size must be greater or equal to the maximum of the high limits of the ranges. (see also parameter). is the log format used when generating syslog messages. It may be one of the following: local Analog to rfc3164 syslog message format except that hostname field is stripped. This is the default. Note: option "log-send-hostname" switches the default to rfc3164. rfc3164 The RFC3164 syslog message format. (https://tools.ietf.org/html/rfc3164) rfc5424 The RFC5424 syslog message format. (https://tools.ietf.org/html/rfc5424) priority A message containing only a level plus syslog facility between angle brackets such as '<63>', followed by the text. The PID, date, time, process name and system name are omitted. This is designed to be used with a local log server. short A message containing only a level between angle brackets such as '<3>', followed by the text. The PID, date, time, process name and system name are omitted. This is designed to be used with a local log server. This format is compatible with what the systemd logger consumes. timed A message containing only a level between angle brackets such as '<3>', followed by ISO date and by the text. The PID, process name and system name are omitted. This is designed to be used with a local log server. iso A message containing only the ISO date, followed by the text. The PID, process name and system name are omitted. This is designed to be used with a local log server. raw A message containing only the text. The level, PID, date, time, process name and system name are omitted. This is designed to be used in containers or during development, where the severity only depends on the file descriptor used (stdout/stderr). name of the optional "log-profile" section that will be considered during the log building process to override some log options. Check out "8.3.5. Log profiles" for more info. must be one of the 24 standard syslog facilities: kern user mail daemon auth syslog lpr news uucp cron auth2 ftp ntp audit alert cron2 local0 local1 local2 local3 local4 local5 local6 local7 Note that the facility is ignored for the "short" and "raw" formats, but still required as a positional field. It is recommended to use "daemon" in this case to make it clear that it's only supposed to be used locally. is optional and can be specified to filter outgoing messages. By default, all messages are sent. If a level is specified, only messages with a severity at least as important as this level will be sent. An optional minimum level can be specified. If it is set, logs emitted with a more severe level than this one will be capped to this level. This is used to avoid sending "emerg" messages on all terminals on some default syslog configurations. Eight levels are known: emerg alert crit err warning notice info debug ``` 请注意,决定从连接中记录哪些内容的是前端,若发生内容切换,则后端生成的日志条目将被忽略。连接日志记录级别为 "info"。 然而,后端日志声明定义了服务器状态变更的记录方式和位置。状态变为“上线”时使用级别“notice”记录,收到终止信号或服务永久终止时使用级别“warning”记录,服务器宕机时使用级别“alert”记录。 请注意:根据 RFC3164,消息在发出前会被截断至 1024 字节。 示例: ```text log global log stdout format short daemon # send log to systemd log stdout format raw daemon # send everything to stdout log stderr format raw daemon notice # send important events to stderr log 127.0.0.1:514 local0 notice # only send important events log tcp@127.0.0.1:514 local0 notice notice # same but limit output # level and send in tcp log "${LOCAL_SYSLOG}:514" local0 notice # send to local server ``` **`log-format `** ```haproxy log-format ``` 指定用于流量日志的自定义日志格式字符串 可用于以下上下文:tcp、http 可出现在以下段中:defaults \| frontend \| listen \| backend yes \| yes \| yes \| no 该指令指定将用于通过此行配置的前端处理流量所产生的所有日志的日志格式字符串。若该指令在 defaults 段中使用,则后续所有前端将采用相同的日志格式。请参见 [section 8.2.6](/zh/docs/haproxy/configuration-logging/#section-8-2-6),其中详细介绍了自定义日志格式字符串。 也可定义仅在连接错误情况下使用的特定日志格式,详见 "error-log-format" 选项。 "log-format" 指令会覆盖之前的 "option tcplog"、"log-format"、"option httplog" 和 "option httpslog" 指令。 **`log-format-sd `** ```haproxy log-format-sd ``` 指定用于生成 RFC5424 结构化数据的自定义日志格式字符串 可用于以下上下文:tcp、http 可出现在以下段中:defaults \| frontend \| listen \| backend yes \| yes \| yes \| no 该指令指定 RFC5424 结构化数据日志格式字符串,该字符串将用于通过此行配置的前端处理流量所产生的所有日志。若该指令在 defaults 段中使用,则后续所有前端均将采用相同的日志格式。请参见 [第 8.2.6 节](/zh/docs/haproxy/configuration-logging/#section-8-2-6),其中深入介绍了日志格式字符串。 有关 RFC5424 结构化数据部分的更多信息,请参见 。 请注意:此日志格式字符串仅适用于将日志格式设置为 "rfc5424" 的记录器。 示例: ```text log-format-sd [exampleSDID@1234\ bytes=\"%B\"\ status=\"%ST\"] ``` **`log-steps `** ```haproxy log-steps ``` 指定在事务处理过程中应在哪些步骤生成日志。 可用于以下上下文:tcp、http 可出现在以下段中:defaults \| frontend \| listen \| backend yes \| yes \| yes \| no 在处理 TCP/HTTP 事务时,HAProxy 可能在处理过程的不同阶段生成日志(例如:接受连接、建立连接、接收请求、发送响应、关闭连接)。 默认情况下,HAProxy 每个事务仅生成一条日志,且仅在日志格式表达式中使用的所有项均满足后才发出日志,这意味着在实际应用中,日志通常在事务结束时发出(HTTP 为响应结束后,TCP 为连接结束后),除非使用了 "option logasap"。 指令 "log-steps" 允许精确控制日志的输出时机,甚至支持为同一事务输出多条日志。特殊值 "all" 可用于启用所有可用的日志来源,从而实现从连接接收至连接关闭的完整事务追踪。也可通过用逗号分隔的名称指定个别日志来源,以选择性地启用日志输出。 常见的日志来源包括:accept、connect、request、response、close。 示例: ```text frontend myfront option httplog log-steps accept,close #only log accept and close for the txn ``` 可直接在日志配置文件中使用以“logging steps”(如 accept、close)指定的日志来源(在 'on' 指令之后)。将“log-steps”与日志配置文件结合使用,能够对 HAProxy 在事务处理过程中自动生成的日志实现细粒度控制,具有很高的实用价值。 此设置仅对前端有效,后端将忽略该设置。 另请参阅:"log-profile" **`log-tag `** ```haproxy log-tag ``` 指定用于所有出站日志的日志标签 可用于以下上下文:tcp、http、log 可出现在以下段中:defaults \| frontend \| listen \| backend yes \| yes \| yes \| yes 设置 syslog 头中的标签字段为该字符串。默认值为全局段中设置的 log-tag,否则为从命令行启动时的程序名称,通常为 "HAProxy"。在同一个主机上运行多个进程时,或在同一个进程中运行多个客户实例时,有时需要加以区分。在后端中,关于服务器启停的日志将使用此标签。作为提示,可以在 defaults 段中设置与托管客户相关的 log-tag,然后将该客户的全部前端和后端配置放在此段中,再在新的 defaults 段中开始配置另一个客户。参见全局段中的 "log-tag" 指令。 **`max-keep-alive-queue `** ```haproxy max-keep-alive-queue ``` 设置用于维持持久连接的服务器队列最大大小 可以用于以下上下文:http 可出现在以下段中:defaults \| frontend \| listen \| backend yes \| no \| yes \| yes HTTP 持久连接会尽可能复用相同的服务器连接,但在某些情况下可能适得其反,例如当某些服务器连接数较多而其他服务器处于空闲状态时。这一点在静态服务器上尤为明显。 本设置的目的是设定一个队列中连接数量的阈值,当超过该阈值时,HAProxy 停止尝试复用同一台服务器,转而优先选择其他服务器。默认值 -1 表示无限制。值为 0 表示持久连接永远不会被排队。对于延迟较低、且对中断持久连接不敏感的近距离服务器,建议使用较低的值(例如,本地静态服务器可使用 10 或更小的值)。对于延迟较高的远程服务器,可能需要更高的值以弥补延迟和/或选择其他服务器的开销。 请注意,此设置对连续发送至同一服务器的响应无影响,即使这些响应需被排队。在收到 401 响应后,它们仍会发送至同一服务器。 另请参见:“option http-server-close”、“option prefer-last-server”、服务器“maxconn”和 cookie 持久性。 **`max-session-srv-conns `** ```haproxy max-session-srv-conns ``` 设置单个客户端会话可保持空闲的最大出站连接数。默认值为 5(精确等于在编译时定义的 MAX_SRV_LIST)。 可用于以下上下文:tcp、http 可出现在以下段中:defaults \| frontend \| listen \| backend yes \| yes \| yes \| no **`maxconn `** ```haproxy maxconn ``` 修复前端的最大并发连接数 可用于以下上下文:tcp、http 可出现在以下段中:defaults \| frontend \| listen \| backend yes \| yes \| yes \| no 参数: ```text is the maximum number of concurrent connections the frontend will accept to serve. Excess connections will be queued by the system in the socket's listen queue and will be served once a connection closes. ``` 如果系统支持,对于大型站点而言,将此限制值设得非常高可能很有用,以便 HAProxy 管理连接队列,而非让客户端处于未响应的连接尝试状态。该值不应超过全局 maxconn。同时请注意,每个连接包含两个 tune.bufsize(默认为 16 kB)的缓冲区,以及一些其他数据,导致每个已建立的连接大约消耗 33 kB 的内存。这意味着,经过适当调优的中等规模系统,配备 1 GB 内存时,可承受约 20000 至 25000 个并发连接。 此外,当 `` 设置为较大值时,服务器可能无法承受如此高的负载,因此通常建议为其分配合理的连接限制。 当该值设置为零时(即默认值),将使用全局的 "maxconn" 值。 另请参阅:"server"、global 段的 "maxconn"、"fullconn" **`mode { tcp|http|log|spop }`** ```haproxy mode { tcp|http|log|spop } ``` 设置实例的运行模式或协议。 可在以下段中使用:defaults \| frontend \| listen \| backend 支持:是 \| 是 \| 是 \| 是 参数: ```text tcp The instance will work in pure TCP mode. A full-duplex connection will be established between clients and servers, and no layer 7 examination will be performed. This is the default mode. It should be used for SSL, SSH, SMTP, ... http The instance will work in HTTP mode. The client request will be analyzed in depth before connecting to any server. Any request which is not RFC-compliant will be rejected. Layer 7 filtering, processing and switching will be possible. This is the mode which brings HAProxy most of its value. haterm The frontend will work in haterm HTTP benchmark mode. This is not supported by backends. See doc/haterm.txt for details. log When used in a backend section, it will turn the backend into a log backend. Such backend can be used as a log destination for any "log" directive by using the "backend@" syntax. Log messages will be distributed to the servers from the backend according to the lb settings which can be configured using the "balance" keyword. Log backends support UDP servers by prefixing the server's address with the "udp@" prefix. Common backend and server features are supported, but not TCP or HTTP specific ones. spop When used in a backend section, it will turn the backend into a spop backend. This mode is mandatory if the backend contains SPOA servers, but when mode is tcp, it will automatically be converted to mode spop if such servers are detected. ``` 进行内容切换时,前端和后端必须处于相同模式(通常为 HTTP),否则配置将被拒绝。 示例: ```text defaults http_instances mode http ``` **`monitor fail { if | unless } `** ```haproxy monitor fail { if | unless } ``` 为监控 HTTP 请求添加一个失败报告条件。 可以用于以下上下文:http 可出现在以下段中:defaults \| frontend \| listen \| backend 否 \| 是 \| 是 \| 否 参数: ```text if the monitor request will fail if the condition is satisfied, and will succeed otherwise. The condition should describe a combined test which must induce a failure if all conditions are met, for instance a low number of servers both in a backend and its backup. unless the monitor request will succeed only if the condition is satisfied, and will fail otherwise. Such a condition may be based on a test on the presence of a minimum number of active servers in a list of backends. ``` 此语句添加一个条件,可强制对监控请求的响应报告失败。默认情况下,当外部组件查询专用于监控的 URI 时,将返回 200 响应。当满足上述任一条件时,HAProxy 将返回 503 而非 200。此机制对于向外部组件报告站点故障非常有用,外部组件可能基于 HAProxy 报告的可用性状态在多个站点间进行路由通告。在此场景中,应依赖包含 "nbsrv" 条件的 ACL。请注意,"monitor fail" 仅在 HTTP 模式下有效。如需调整,可使用 "errorfile" 或 "errorloc" 自定义状态消息。 示例: ```text frontend www mode http acl site_dead nbsrv(dynamic) lt 2 acl site_dead nbsrv(static) lt 2 monitor-uri /site_alive monitor fail if site_dead ``` 另请参阅:"monitor-uri"、"errorfile"、"errorloc" **`monitor-uri `** ```haproxy monitor-uri ``` 拦截外部组件监控请求所使用的 URI 可以用于以下上下文:http 可出现在以下段中:defaults \| frontend \| listen \| backend yes \| yes \| yes \| no 参数: ```text is the exact URI which we want to intercept to return HAProxy's health status instead of forwarding the request. ``` 当在前端接收到引用 `` 的 HTTP 请求时,HAProxy 不会转发该请求,也不会记录日志,而是返回“HTTP/1.0 200 OK”或“HTTP/1.0 503 服务不可用”,具体取决于通过“monitor fail”定义的故障条件。通常情况下,任何前端 HTTP 探针均可据此判断服务处于正常运行状态,而无需将请求转发至后端服务器。请注意,HTTP 方法、版本及所有头字段均被忽略,但请求在 HTTP 层面必须至少有效。该关键字仅可与 HTTP 模式前端一同使用。 监控请求在解析后立即处理,甚至早于任何 "http-request" 规则。在此之前仅应用了 tcp-request 规则集。这些请求无法被记录,这是设计目的。监控仅可配置一个 URI;当存在多个 "monitor-uri" 语句时,最后一个将决定所使用的 URI。它们仅用于向高层组件报告 HAProxy 的健康状态,除此之外无其他用途。然而,可以使用 "monitor fail" 和 ACLs 添加任意数量的条件,从而根据任何可设想的检查结果进行调整(最常见的场景是后端中可用服务器的数量)。 请注意:如果 `` 以斜杠('/')开头,则匹配将基于请求路径而非请求 URI 执行。此做法为一种变通方案,用于使 HTTP/2 请求能够匹配 monitor-uri。在 HTTP/2 中,客户端被建议仅发送绝对 URI。 示例: ```shell # Use /haproxy_test to report HAProxy's status frontend www mode http monitor-uri /haproxy_test ``` 另请参见:“monitor fail” **`option abortonclose`** ```haproxy option abortonclose no option abortonclose ``` 启用或禁用客户端关闭时对未开始处理的早期中止 可用于以下上下文:tcp、http 可出现在以下段中:defaults \| frontend \| listen \| backend yes \| yes \| yes \| yes 参数:无 TCP 连接支持在每个方向上独立关闭,仅单向关闭的连接通常被称为“半关闭”。最初,在 HTTP 生态系统主要采用“关闭模式”时,每个连接仅传输一次请求和一次响应后即关闭,此时脚本化客户端发送请求后关闭发送方向,等待响应,接收关闭指示后即完成操作的情况十分常见。然而,随着持久连接及更高级协议的出现,这种做法已基本消失。目前,客户端在未收到响应前关闭连接的情况,本质上仅出现在用户希望中止传输,或超时触发导致连接被关闭的场景中。 这两种情况(半关闭与中止)从服务器端(此处为 HAProxy 监听器)无法区分。这是一个问题,因为当客户端中止连接后仍保持连接并继续处理请求,会消耗大量资源,尤其是当连接关闭是由于用户点击“重载”按钮所致时,意味着新请求被排队,而先前的请求并未被中止。反之,若在遇到此类半关闭情况时一律中止连接,将导致大量 TCP 应用程序以及部分内部网络中与旧版代理交互的 HTTP 应用程序无法正常工作。 abortonclose 选项 "abortonclose" 选项允许选择期望的行为:当该选项存在于前端时,将避免处理处于半关闭连接上的待处理 TLS 握手。这可能是由于用户在高负载下执行 HTTPS 请求时触发“重载”操作,例如在主 HAProxy 节点与备用节点之间发生 VRRP 故障转移时:所有客户端同时重新连接至新节点,且所有客户端均需执行开销较高的完整 TLS 握手。若该过程耗时超过数秒,很可能导致部分用户放弃连接,此时继续为其执行握手将毫无意义。鉴于 TLS 握手的 CPU 开销较高,建议在面向互联网的前端上保持该选项启用。对于入站 TLS 连接,此为默认行为。 - when present in a backend, it will cause half-closed connections to try to abort a request that was not yet sent to a server (i.e. when it's pending in the queue or when trying to connect). If the request is already being served by a server, then the connection to the server is in turn switched to half-close to indicate the same condition to the server, which will then decide how to proceed. This is the default for HTTP-mode backends. 建议在面向互联网的 TLS 终端节点和 HTTP 服务上启用此选项,并在纯 TCP 服务以及未暴露的旧环境里禁用。HTTP 后端中默认启用此选项,可通过在后端段或其继承的“defaults”段中前置“no”关键字强制禁用。TLS 监听器也默认启用此选项,同样可通过在前端段或其继承的“defaults”段中指定“no option abortonclose”强制禁用。 如果该选项在“defaults”段中已启用,可以在特定实例中通过在其前添加“no”关键字来禁用。 另请参见:“timeout queue” 以及服务器的 “maxconn” 和 “maxqueue” 参数 **`option accept-invalid-http-request (deprecated)`** ```haproxy option accept-invalid-http-request (deprecated) no option accept-invalid-http-request (deprecated) ``` 启用或禁用对 HTTP 请求解析的宽松处理 “accept-invalid-http-request” 关键字已弃用,请改用 “option accept-unsafe-violations-in-http-request”。 **`option accept-invalid-http-response (deprecated)`** ```haproxy option accept-invalid-http-response (deprecated) no option accept-invalid-http-response (deprecated) ``` 启用或禁用对 HTTP 响应解析的宽松处理 "accept-invalid-http-response" 关键字已弃用,请改用 "option accept-unsafe-violations-in-http-response"。 **`option accept-unsafe-violations-in-http-request`** ```haproxy option accept-unsafe-violations-in-http-request no option accept-unsafe-violations-in-http-request ``` 启用或禁用对 HTTP 请求解析的宽松处理 可以用于以下上下文:http 可出现在以下段中:defaults \| frontend \| listen \| backend yes \| yes \| yes \| no 参数:无 默认情况下,HAProxy 会遵循不同的 HTTP RFC 规范进行消息解析。这意味着消息解析非常严格,对于格式错误的消息会向客户端返回错误。这种行为是期望的,因为格式错误的消息本质上常被用于利用服务器弱点的攻击,或绕过安全过滤。有时,由于某种原因(配置、实现等),某些存在缺陷的浏览器可能不遵守这些 RFC,而问题不会立即得到修复。在此情况下,可以通过指定该选项来放宽 HAProxy 的解析规则,以接受部分无效请求。大多数规则出于历史原因主要针对 H1 解析。较新的 HTTP 版本趋向于更加规范,应用程序也更严格地遵循这些协议。 当设置此选项时,遵循以下规则: * In H1 only, invalid characters, including NULL character, in header name will not be rejected; however the header will be dropped. * In H1 only, NULL character in header value will be accepted; * In H1 only, characters above 127 in the URI will be accepted. The list of characters allowed to appear in a URI is well defined by RFC3986, and chars 0-31, 32 (space), 34 ('"'), 60 ('<'), 62 ('>'), 92 ('\'), 94 ('^'), 96 ('`'), 123 ('{'), 124 ('|'), 125 ('}'), 127 (delete) and anything above are normally not allowed. In H1, all character between (0..32) and 127 will always be blocked. All characters above 127 (excluded) will also be blocked, except when this option is enabled. Other characters (33..126) will not be checked at all. * In H1 and H2, URLs containing fragment references ('#' after the path) will be accepted; * In H1 only, no check will be performed on the authority for CONNECT requests; * In H1 only, no check will be performed against the authority and the Host header value. * In H1 only, tests on the HTTP version will be relaxed. It will allow HTTP/0.9 GET requests to pass through (no version specified), as well as different protocol names (e.g. RTSP), and multiple digits for both the major and the minor version. * In H1 only, WebSocket (RFC6455) requests failing to present a valid "Sec-Websocket-Key" header field will be accepted. 此选项默认情况下绝不可启用,因为它会隐藏应用程序的缺陷和安全漏洞。仅在确认问题存在后方可部署。 启用此选项后,无效但被接受的 H1 请求将被捕获,以便后续通过 UNIX 统计套接字上的 "show errors" 请求进行分析。执行此操作还有助于确认问题已解决。 如果该选项在“defaults”段中已启用,可以在特定实例中通过在其前添加“no”关键字来禁用。 另请参阅:stats 套接字上的“option accept-unsafe-violations-in-http-response” 和 “show errors”。 **`option accept-unsafe-violations-in-http-response`** ```haproxy option accept-unsafe-violations-in-http-response no option accept-unsafe-violations-in-http-response ``` 启用或禁用对 HTTP 响应解析的宽松处理 可以用于以下上下文:http 可出现在以下段中:defaults \| frontend \| listen \| backend yes \| no \| yes \| yes 参数:无 与“option accept-unsafe-violations-in-http-request”类似,此选项可用于放宽对 HTTP 响应的解析规则。仅当目标服务器为可信的旧版服务器时,才应启用此选项以接受部分无效响应。大多数规则出于历史原因针对 H1 解析。较新的 HTTP 版本通常更为规范,应用程序也更严格遵循这些协议。 当设置此选项时,遵循以下规则: * In H1 only, status codes longer than 3 digits but whose value fits in 16 bits are not rejected. * In H1 only, invalid characters, including NULL character, in header name will not be rejected; however the header will be dropped. * In H1 only, NULL character in header value will be accepted; * In H1 only, empty values or several "chunked" value occurrences for Transfer-Encoding header will be accepted; * In H1 only, no check will be performed against the authority and the Host header value. * In H1 only, tests on the HTTP version will be relaxed. It will allow different protocol names (e.g. RTSP), and multiple digits for both the major and the minor version. * In H1 only, WebSocket (RFC6455) responses failing to present a valid "Sec-Websocket-Accept" header field will be accepted. 此选项默认情况下绝不可启用,因为它会隐藏应用程序的缺陷和安全漏洞。仅在确认问题存在后方可部署。 启用此选项后,响应中的错误头名称仍会被接受,但会完整捕获响应内容,以便后续通过 UNIX 统计套接字上的 "show errors" 请求进行分析。执行此操作还有助于确认问题已解决。 如果该选项在“defaults”段中已启用,可以在特定实例中通过在其前添加“no”关键字来禁用。 另请参阅:stats 套接字上的“option accept-unsafe-violations-in-http-request”和“show errors”。 **`option allbackups`** ```haproxy option allbackups no option allbackups ``` 可同时使用所有备用服务器,或仅使用第一个备用服务器。 可用于以下上下文:tcp、http、log 可出现在以下段中:defaults \| frontend \| listen \| backend yes \| no \| yes \| yes 参数:无 默认情况下,当所有正常服务器均不可用时,首个处于运行状态的备用服务器将接收全部流量。 有时可能更希望同时使用多个备用服务器,因为仅使用一个可能不够。当启用 "option allbackups" 时,若所有正常服务器均不可用,负载均衡将在所有备用服务器之间进行。将使用相同的负载均衡算法,并尊重服务器的权重。因此,备用服务器之间将不再存在优先级顺序。 该选项通常用于静态服务器集群,当应用程序完全离线时,返回“抱歉”页面。 如果该选项在“defaults”段中已启用,可以在特定实例中通过在其前添加“no”关键字来禁用。 **`option checkcache`** ```haproxy option checkcache no option checkcache ``` 分析所有服务器响应,并阻止包含可缓存 Cookie 的响应 可以用于以下上下文:http 可出现在以下段中:defaults \| frontend \| listen \| backend yes \| no \| yes \| yes 参数:无 某些高级框架会在所有位置设置应用 Cookie,且并不总是为开发者提供足够的控制权,以管理响应的缓存方式。当缓存对象返回会话 Cookie 时,用户通过相同缓存时发生会话交叉或窃取的风险极高。在某些情况下,阻止响应比让敏感会话信息暴露在外更为妥当。 选项 "checkcache" 启用对所有服务器响应的深度检查,以确保其严格符合 HTTP 规范中关于可缓存性的要求。该选项会仔细检查服务器响应中的 "Cache-Control"、"Pragma" 和 "Set-Cookie" 头,以判断是否存在客户端代理缓存 Cookie 的风险。启用此选项后,仅以下响应可传递给客户端: - 所有不含 "Set-Cookie" 头的响应; - 所有返回码非 200、203、204、206、300、301、404、405、410、414、501 的响应,前提是服务器未设置 "Cache-Control: public" 头字段; - 所有通过非 GET、HEAD、OPTIONS、TRACE 方法发起的请求所导致的响应,前提是服务器未设置 "Cache-Control: public" 头字段; - 所有包含 "Pragma: no-cache" 头的响应; - 所有包含 "Cache-Control: private" 头的响应; - 所有包含 "Cache-Control: no-store" 头的响应; - 所有包含 "Cache-Control: max-age=0" 头的响应; - 所有包含 "Cache-Control: s-maxage=0" 头的响应; - 所有包含 "Cache-Control: no-cache" 头的响应; - 所有包含 "Cache-Control: no-cache=\"set-cookie\"" 头的响应; - 所有包含 "Cache-Control: no-cache=\"set-cookie," 头的响应(允许 "set-cookie" 之后包含其他字段)。 如果响应不满足这些要求,则其将被阻止,效果等同于来自 "http-response deny" 规则的响应,返回 "HTTP 502 bad gateway"。会话状态显示为 "PH--",表示代理在处理头时阻断了响应。此外,日志中将发送告警,以便管理员知晓需进行修复。 由于该选项对应用影响较大,应用在上线生产环境前应充分测试启用该选项的情况。在测试过程中,即使生产环境不使用该选项,也建议始终启用,以便报告潜在危险的应用行为。 如果该选项在“defaults”段中已启用,可以在特定实例中通过在其前添加“no”关键字来禁用。 **`option clitcpka`** ```haproxy option clitcpka no option clitcpka ``` 启用或禁用在客户端侧发送 TCP keepalive 数据包 可用于以下上下文:tcp、http 可出现在以下段中:defaults \| frontend \| listen \| backend yes \| yes \| yes \| no 参数:无 当客户端与服务器之间存在防火墙或其他会话感知组件,且协议涉及长时间会话及较长空闲期(例如远程桌面)时,中间组件可能因会话空闲时间过长而决定终止该会话,从而带来风险。 启用套接字级别的 TCP 持久连接可使系统定期向连接的另一端发送数据包,从而保持连接处于活跃状态。持久连接探测之间的延迟由系统控制,且取决于操作系统及其调优参数。 必须理解,持久连接报文不会在应用层发出或接收,仅网络协议栈能够感知到它们。因此,即使代理的一端已使用持久连接来维持连接活跃,这些持久连接报文也不会被转发至代理的另一端。 请注意,这与 HTTP 持久连接无关。 使用选项 "clitcpka" 可在连接的客户端一侧启用 TCP 持久连接探测,当 HAProxy 与客户端之间的会话超时被察觉时,此功能应能提供帮助。 如果该选项在“defaults”段中已启用,可以在特定实例中通过在其前添加“no”关键字来禁用。 另请参阅:“option srvtcpka”、“option tcpka” **`option contstats`** ```haproxy option contstats ``` 启用持续的流量统计信息更新 可用于以下上下文:tcp、http 可出现在以下段中:defaults \| frontend \| listen \| backend yes \| yes \| yes \| no 参数:无 默认情况下,用于统计信息计算的计数器仅在流结束时才递增。在提供小对象时,该机制工作良好;但在处理大对象(例如大型图片或归档文件)或音视频流时,由 HAProxy 计数器生成的图表会呈现类似刺猬的形态。启用此选项后,计数器会在流过程中频繁递增,通常每 5 秒一次,这通常足以生成清晰的图表。由于重新计数会直接触碰热点路径,因此默认不启用,因为这可能导致会话数量极大时产生大量唤醒,从而造成轻微性能下降。 **`option disable-h2-upgrade`** ```haproxy option disable-h2-upgrade no option disable-h2-upgrade ``` 启用或禁用从 HTTP/1.x 客户端连接隐式升级至 HTTP/2。 可以用于以下上下文:http 可出现在以下段中:defaults \| frontend \| listen \| backend yes \| yes \| yes \| no 参数:无 默认情况下,HAProxy 能够在从特定 HTTP 连接接收到的首个请求与 HTTP/2 连接前缀匹配时,隐式将 HTTP/1.x 客户端连接升级为 HTTP/2 连接(即字符串 "PRI \* HTTP/2.0\r\n\r\nSM\r\n\r\n")。 通过这种方式,可在非 SSL 连接上同时支持 HTTP/1.x 与 HTTP/2 客户端。 必须使用此选项以禁用隐式升级。 请注意,此隐式升级仅支持 HTTP 代理,因此该选项也仅适用于 HTTP 代理。 此外,可通过在 bind 行指定 "proto h2" 强制在明文连接上启用 HTTP/2。 最后,此选项适用于所有 bind 行。 如需禁用特定 bind 行的隐式 HTTP/2 升级,可使用 "proto h1"。 如果该选项在“defaults”段中已启用,可以在特定实例中通过在其前添加“no”关键字来禁用。 **`option dontlog-normal`** ```haproxy option dontlog-normal no option dontlog-normal ``` 启用或禁用正常、成功的连接日志记录 可用于以下上下文:tcp、http 可出现在以下段中:defaults \| frontend \| listen \| backend yes \| yes \| yes \| no 参数:无 某些大型站点每秒需处理数千个连接,日志记录成为一大难题。部分站点甚至被迫关闭日志功能,无法对生产环境问题进行调试。启用此选项后,正常连接(即未发生错误、超时、重试或重分派的连接)将不会被记录。此举可为异常情况保留磁盘空间。在 HTTP 模式下,将检查响应状态码,状态码为 5xx 的响应仍会被记录。 强烈不建议使用此选项,因为大多数情况下,复杂问题的关键信息存在于常规日志中,而这些日志不会在此处记录。如需分离日志,请改用 `log-separate-errors` 选项。 另请参阅:“log”、“dontlognull”、“log-separate-errors”以及 [第 8 节](/zh/docs/haproxy/configuration-logging/) 中关于日志记录的内容。 **`option dontlognull`** ```haproxy option dontlognull no option dontlognull ``` 启用或禁用空连接日志记录 可用于以下上下文:tcp、http 可出现在以下段中:defaults \| frontend \| listen \| backend yes \| yes \| yes \| no 参数:无 在某些环境中,存在一些组件会定期连接到各个系统,以确保其仍处于活跃状态。这可能是来自另一台负载均衡器,也可能是来自监控系统。默认情况下,即使是一个简单的端口探测或扫描也会产生日志。如果这些连接导致日志过于冗杂,可以启用选项 `dontlognull`,以指示未传输任何数据的连接将不会被记录,这通常对应于此类探测。请注意,错误仍会返回给客户端,并计入统计信息。若不希望如此,可改用选项 `http-ignore-probes`。 在不受控制的环境(例如互联网)中,通常不建议使用此选项,否则扫描及其他恶意活动将不会被记录。 如果该选项在“defaults”段中已启用,可以在特定实例中通过在其前添加“no”关键字来禁用。 另请参阅:“log”、“http-ignore-probes”、“monitor-uri”以及关于日志记录的[第 8 节](/zh/docs/haproxy/configuration-logging/)。 **`option external-check`** ```haproxy option external-check ``` 使用外部进程进行服务器健康检查 可用于以下上下文:tcp、http、log 可出现在以下段中:defaults \| frontend \| listen \| backend yes \| no \| yes \| yes 可以使用外部命令测试服务器的健康状态。这通过运行使用 "external-check command" 设置的可执行文件来实现。 必须设置全局选项 "external-check"。 另请参阅: "external-check"、"external-check command"、"external-check path" **`option forwarded [ proto ]`** ```haproxy option forwarded [ proto ] [ host | host-expr ] [ by | by-expr ] [ by_port | by_port-expr ] [ for | for-expr ] [ for_port | for_port-expr ] no option forwarded ``` 启用在发送至服务器的请求中插入 rfc 7239 forwarded 头 可以用于以下上下文:http 可出现在以下段中:defaults \| frontend \| listen \| backend yes \| no \| yes \| yes 参数: ```text optional argument to specify a custom sample expression those result will be used as 'host' parameter value optional argument to specify a custom sample expression those result will be used as 'by' parameter nodename value optional argument to specify a custom sample expression those result will be used as 'for' parameter nodename value optional argument to specify a custom sample expression those result will be used as 'by' parameter nodeport value optional argument to specify a custom sample expression those result will be used as 'for' parameter nodeport value ``` 由于 HAProxy 以反向代理模式运行,服务器会丢失部分请求上下文(例如请求来源:客户端 IP 地址、所用协议等...) 一种常见的应对此限制的方法是使用广为人知的 X-Forwarded-For 和 X-Forwarded-* 等头字段,将部分上下文信息暴露给底层服务器或应用程序。尽管过去该方法曾有效且广泛部署,但并未得到 IETF 的官方支持,可能引发互操作性及安全问题。 为解决此问题,IETF 已定义了一种新的 HTTP 扩展:forwarded 头(RFC7239)。更多信息请参见 此单一头字段的使用可在同一头中传递大量信息,且最重要的是,解决了代理链问题。(RFC 允许多个级联代理向已存在的头字段追加各自的值。) 该选项可在 defaults、listen 或 backend 段中指定,但在 frontend 段中将被忽略。 设置选项 forwarded 且不带参数时,将使用默认隐式行为。默认行为启用 proto 参数,并注入原始客户端 IP。 等效的显式/手动配置如下: ```text option forwarded proto for ``` 关键字 'by' 用于在转发头中启用 'by' 参数("nodename")。该功能允许嵌入请求代理信息。若不可用(例如:UNIX 监听器),'by' 值将设为 "unknown"。 关键字 'by-expr' 用于在转发头中启用 'by' 参数("nodename")。它允许嵌入请求代理信息。若样本表达式 `` 有效,则 'by' 值将被设置为该表达式的计算结果;否则,将被设置为 "unknown"。 关键字 'for' 用于在转发头中启用 'for' 参数("nodename")。它允许嵌入请求客户端信息。若不可用(例如:UNIX 监听器),'for' 值将设为 "unknown"。 关键字 'for-expr' 用于在转发头中启用 'for' 参数("nodename")。它允许嵌入请求客户端信息。若样本表达式 `` 有效,则 'for' 值将被设置为该表达式的计算结果;否则,将被设置为 "unknown"。 关键字 'by_port' 用于向 'by' 参数提供“nodeport”信息。'by_port' 要求必须设置 'by' 或 'by-expr',否则将被忽略。若可用,“nodeport”将被设为代理(目标)端口,否则将被忽略。 关键字 'by_port-expr' 用于向 'by' 参数提供“nodeport”信息。'by_port-expr' 要求必须设置 'by' 或 'by-expr',否则将被忽略。若样本表达式 `` 有效,“nodeport”将被设置为该表达式的计算结果,否则将被忽略。 关键字 'for_port' 用于向 'for' 参数提供“nodeport”信息。'for_port' 要求必须设置 'for' 或 'for-expr',否则将被忽略。“nodeport”将在可用时设为客户端(源)端口,否则将被忽略。 关键字 'for_port-expr' 用于向 'for' 参数提供“nodeport”信息。'for_port-expr' 要求必须设置 'for' 或 'for-expr',否则将被忽略。“nodeport”将被设置为样本表达式 `` 的结果(若有效),否则将被忽略。 示例: ```shell # Those servers want the ip address and protocol of the client request # Resulting header would look like this: # forwarded: proto=http;for=127.0.0.1 backend www_default mode http option forwarded #equivalent to: option forwarded proto for # Those servers want the requested host and hashed client ip address # as well as client source port (you should use seed for xxh32 if ensuring # ip privacy is a concern) # Resulting header would look like this: # forwarded: host="haproxy.org";for="_000000007F2F367E:60138" backend www_host mode http option forwarded host for-expr src,xxh32,hex for_port # Those servers want custom data in host, for and by parameters # Resulting header would look like this: # forwarded: host="host.com";by=_haproxy;for="[::1]:10" backend www_custom mode http option forwarded host-expr str(host.com) by-expr str(_haproxy) for for_port-expr int(10) # Those servers want random 'for' obfuscated identifiers for request # tracing purposes while protecting sensitive IP information # Resulting header would look like this: # forwarded: for=_000000002B1F4D63 backend www_for_hide mode http option forwarded for-expr rand,hex ``` 另请参阅:"option forwardfor"、"option originalto" **`option forwardfor [ except ] [ header ] [ if-none ]`** ```haproxy option forwardfor [ except ] [ header ] [ if-none ] ``` 启用向发送至服务器的请求插入 X-Forwarded-For 头 可以用于以下上下文:http 可出现在以下段中:defaults \| frontend \| listen \| backend yes \| yes \| yes \| yes 参数: ```text is an optional argument used to disable this option for sources matching an optional argument to specify a different "X-Forwarded-For" header name. ``` 由于 HAProxy 以反向代理模式运行,服务器看到的客户端地址为其 IP 地址。 当服务器日志需要记录客户端的真实 IP 地址时,这种情况有时会造成困扰。为解决此问题,HAProxy 可在发送至服务器的所有请求中添加知名的 HTTP 头 “X-Forwarded-For”。该头包含表示客户端 IP 地址的值。由于此头始终被追加到现有头列表的末尾,服务器必须配置为仅使用该头的最后一个出现位置。请参阅服务器手册,了解如何启用对这一标准头的使用。请注意,仅应使用该头的最后一个出现位置,因为客户端可能已携带了该头。 关键字 "header" 可用于指定一个不同的头名称,以替代默认的 "X-Forwarded-For"。当可能已从其他应用(例如 stunnel)接收到 "X-Forwarded-For" 头时,此功能非常有用,可确保保留原有头信息。此外,若后端服务器不使用 "X-Forwarded-For" 头,而需要其他头(例如 Zeus Web 服务器要求使用 "X-Cluster-Client-IP"),也可通过此方式指定。 有时,同一个 HAProxy 实例可能同时用于直接客户端访问和反向代理访问(例如,当使用 SSL 反向代理解密 HTTPS 流量时)。可以通过添加 "except" 关键字并指定网络地址,禁用对已知源地址或网络的头信息添加。在此情况下,任何与该网络匹配的源 IP 都不会触发该头信息的添加。常见用法包括私有网络或 127.0.0.1。支持 IPv4 和 IPv6。 此外,关键字 "if-none" 表示仅当该头不存在时才添加该头。 此选项仅应在完全可信的环境中使用,因为如果传入 HAProxy 的头由终端用户控制,可能会引发安全问题。 该选项可在前端或后端中指定。若其中至少一个使用了该选项,将添加对应头信息。请注意,若前端和后端均定义了该头信息的子参数,则后端的设置优先于前端。对于 "if-none" 参数,若前端或后端中至少有一方未指定该参数,则其要求添加操作为强制性,因此该方优先。 示例: ```shell # Public HTTP address also used by stunnel on the same machine frontend www mode http option forwardfor except 127.0.0.1 # stunnel already adds the header # Those servers want the IP Address in X-Client backend www mode http option forwardfor header X-Client ``` 另请参阅:“option httpclose”、“option http-server-close”、“option http-keep-alive” **`option h1-case-adjust-bogus-client`** ```haproxy option h1-case-adjust-bogus-client no option h1-case-adjust-bogus-client ``` 启用或禁用向伪造客户端发送的 HTTP/1 头的大小写调整 可以用于以下上下文:http 可出现在以下段中:defaults \| frontend \| listen \| backend yes \| yes \| yes \| no 参数:无 由于 RFC7230 明确指出,头名称没有标准大小写形式,因此其大小写不敏感。 应用程序必须以不区分大小写的方式处理头名称。 但某些不合规的应用程序违反标准,错误地依赖浏览器通常使用的大小写形式。 这一问题在 HTTP/2 中变得尤为关键,因为所有头名称必须以小写形式传输,HAProxy 也遵循相同约定。 无论 HTTP 版本为何,所有头名称均以小写形式发送给客户端和服务器。 当 HAProxy 收到 HTTP/1 响应时,其头名称会被转换为小写形式,经处理后以该格式发送给客户端。若已知某客户端违反 HTTP 标准,且无法正确处理来自 HAProxy 的响应,则可通过启用此选项,并使用全局指令 h1-case-adjust 或 h1-case-adjust-file 指定需重新格式化的头列表,将小写头名称转换为其他格式后再发送给客户端。此操作仅应作为临时解决方案,待客户端修复期间使用,因为依赖此类 workaround 的客户端可能易受内容伪装攻击,必须彻底修复。 请注意,此选项不会影响符合标准的客户端。 如果该选项在“defaults”段中已启用,可以在特定实例中通过在其前添加“no”关键字来禁用。 另请参阅:“option h1-case-adjust-bogus-server”、“h1-case-adjust”、“h1-case-adjust-file”。 **`option h1-case-adjust-bogus-server`** ```haproxy option h1-case-adjust-bogus-server no option h1-case-adjust-bogus-server ``` 启用或禁用向伪造服务器发送的 HTTP/1 头的大小写调整 可以用于以下上下文:http 可出现在以下段中:defaults \| frontend \| listen \| backend yes \| no \| yes \| yes 参数:无 由于 RFC7230 明确指出,头名称没有标准大小写形式,因此其大小写不敏感。 应用程序必须以不区分大小写的方式处理头名称。 但某些不合规的应用程序违反标准,错误地依赖浏览器通常使用的大小写形式。 这一问题在 HTTP/2 中变得尤为关键,因为所有头名称必须以小写形式传输,HAProxy 也遵循相同约定。 无论 HTTP 版本为何,所有头名称均以小写形式发送给客户端和服务器。 当 HAProxy 收到 HTTP/1 请求时,其请求头名称会被转换为小写形式,并以该格式发送至服务器。若已知某服务器违反 HTTP 标准,无法正确处理来自 HAProxy 的请求,则可通过启用此选项,并使用全局指令 `h1-case-adjust` 或 `h1-case-adjust-file` 指定需重新格式化的请求头列表,将小写请求头名称转换为其他格式后再发送至服务器。此操作仅应作为临时解决方案,用于等待服务器修复的过渡期间,因为依赖此类 workaround 的服务器可能易受内容伪装攻击,必须彻底修复。 请注意,此选项不会影响符合标准的服务器。 如果该选项在“defaults”段中已启用,可以在特定实例中通过在其前添加“no”关键字来禁用。 另请参阅:“option h1-case-adjust-bogus-client”、“h1-case-adjust”、“h1-case-adjust-file”。 **`option http-buffer-request`** ```haproxy option http-buffer-request no option http-buffer-request ``` 启用或禁用在继续处理前等待接收完整的 HTTP 请求体 可以用于以下上下文:http 可出现在以下段中:defaults \| frontend \| listen \| backend yes \| yes \| yes \| yes 参数:无 有时需要在获取 HTTP 请求体之后再做出决策。例如,“balance url_param” 就是这样做的。第一个用例是在连接到服务器之前,缓冲来自慢速客户端的请求。第二个用例是根据请求体的内容做出路由决策。在前端或后端中设置此选项,将强制 HTTP 处理等待,直到接收完整个请求体或请求缓冲区已满。对于某些滥用 HTTP 协议、期望前端与后端之间实现无缓冲传输的应用程序,此选项可能产生不良副作用,因此应务必避免默认启用。 另请参阅:“option http-no-delay”、“timeout http-request”、“http-request wait-for-body” **`option http-drop-request-trailers`** ```haproxy option http-drop-request-trailers no option http-drop-request-trailers ``` 从请求发送至服务器时移除 HTTP trailers 可以用于以下上下文:http 可出现在以下段中:defaults \| frontend \| listen \| backend yes \| no \| no \| yes 参数:无 启用此选项后,请求中发现的任何 HTTP 追随者(trailers)将在发送至服务器前被丢弃。 RFC9110#section-6.5.1 指出,尾部字段可以与头字段合并。这应为有意为之,但可能对某些应用程序造成问题,尤其是当恶意客户端将敏感头字段隐藏在尾部部分,而某些中间节点在未进行特定检查的情况下将其与头字段合并时。在此情况下,可在后端启用此选项,以在将请求发送至服务器前丢弃任何发现的尾部字段。 如果该选项在“defaults”段中已启用,可以在特定实例中通过在其前添加“no”关键字来禁用。 另请参见:"option http-drop-response-trailers" **`option http-drop-response-trailers`** ```haproxy option http-drop-response-trailers no option http-drop-response-trailers ``` 从响应中移除 HTTP trailers 后再发送给客户端 可以用于以下上下文:http 可出现在以下段中:defaults \| frontend \| listen \| backend yes \| yes \| yes \| no 参数:无 此选项与“option http-drop-request-trailers”类似,但必须用于在向客户端发送响应前丢弃响应中的尾部字段。 如果该选项在“defaults”段中已启用,可以在特定实例中通过在其前添加“no”关键字来禁用。 另请参阅:"option http-drop-request-trailers" **`option http-ignore-probes`** ```haproxy option http-ignore-probes no option http-ignore-probes ``` 启用或禁用对空连接和请求超时的日志记录 可以用于以下上下文:http 可出现在以下段中:defaults \| frontend \| listen \| backend yes \| yes \| yes \| no 参数:无 最近,一些浏览器开始实现“预连接”功能,即在用户可能访问最近浏览过的网站时,预先建立连接。这导致大量连接被建立到网站,若超时先触发,则结果为 408 请求超时;若浏览器先决定关闭连接,则结果为 400 错误请求。这些情况会污染日志并增加错误计数器。虽然已有“option dontlognull”,但在此场景下仍不充分。相反,此选项执行以下操作:— 若连接关闭前未收到任何数据,则阻止向客户端发送任何 400/408 消息;— 在此情况下阻止生成任何日志;— 阻止任何错误计数器被递增 这样,空连接将被静默忽略。请注意,除非明确需要,否则不建议使用此选项,因为它会隐藏真实问题。未收到请求并看到 408 错误的最常见原因是客户端与中间设备(如 VPN)之间存在 MTU 不一致,导致过大数据包被阻断。此类问题通常也出现在 POST 请求以及携带大 Cookie 的 GET 请求中。日志通常是检测此类问题的唯一途径。 如果该选项在“defaults”段中已启用,可以在特定实例中通过在其前添加“no”关键字来禁用。 另请参阅:“log”、“dontlognull”、“errorfile”以及 [第 8 节](/zh/docs/haproxy/configuration-logging/) 中关于日志记录的内容。 **`option http-keep-alive`** ```haproxy option http-keep-alive no option http-keep-alive ``` 启用或禁用客户端到服务器的 HTTP/1.x 连接中的 HTTP 持久连接 可以用于以下上下文:http 可出现在以下段中:defaults \| frontend \| listen \| backend yes \| yes \| yes \| yes 参数:无 默认情况下,HAProxy 以持久连接模式处理 HTTP/1.x 的持久连接:对于每个连接,它会处理每个请求和响应,并在两端保持连接空闲。可通过多个选项更改此模式,例如“option http-server-close”或“option httpclose”。此选项可恢复持久连接模式,当在 defaults 段中使用了其他模式时,此功能尤为有用。 设置 "option http-keep-alive" 可在客户端和服务器端启用 HTTP 持久连接模式。该模式在客户端侧可实现最低延迟(尤其适用于慢速网络),在服务器侧可实现最快会话复用,但需以维持与服务器的空闲连接为代价。通常情况下,使用此选项可使小对象的请求速率大约达到 "http-server-close" 选项的两倍。此选项主要适用于以下两种场景: - when the server is non-HTTP compliant and authenticates the connection instead of requests (e.g. NTLM authentication) - when the cost of establishing the connection to the server is significant compared to the cost of retrieving the associated object from the server. 最后一种情况可能出现在服务器是快速静态缓存服务器时。 目前,日志不会标明请求是否来自同一会话。日志中报告的接受时间对应于前一个请求的结束时间,请求时间对应于等待新请求所花费的时间。若未设置,持久连接的请求时间仍受 "timeout http-keep-alive" 或 "timeout http-request" 定义的超时限制。 此选项会禁用并替换任何先前配置的 "option httpclose" 或 "option http-server-close"。 另请参阅:“option httpclose”、“option http-server-close”、“option prefer-last-server”和“option http-pretend-keepalive”。 **`option http-no-delay`** ```haproxy option http-no-delay no option http-no-delay ``` 请系统优先考虑较低的交互延迟,而非 HTTP 性能。 可以用于以下上下文:http 可出现在以下段中:defaults \| frontend \| listen \| backend yes \| yes \| yes \| yes 参数:无 在 HTTP 中,每个数据负载均为单向传输,且不涉及交互性概念。任何代理都应合理地对数据进行排队,以保证较低的延迟。极少数服务器到服务器的应用程序滥用 HTTP 协议,期望数据负载阶段具有高度交互性,即在单个请求中双向交错传输大量数据块。这完全不符合 HTTP 规范,且在大多数代理或服务器上无法正常工作。当此类应用程序通过 HAProxy 尝试实现时,虽然可以运行,但由于网络优化机制倾向于通过等待足够数据以发送完整数据包来提升性能,因此会遭遇显著延迟。典型延迟约为每往返一次 200 毫秒。请注意,这种情况仅出现在异常使用场景中。正常使用场景,如 CONNECT 请求或 WebSocket,不受影响。 当“option http-no-delay”出现在连接所使用的前端或后端中时,所有此类优化都将被禁用,以实现最快的数据交换。当然,这并不能保证功能正常,因为可能在其他任何位置出现故障。但如果应用程序通过 HAProxy 可以正常工作,那么其性能将达到最优。该选项不应默认启用,除非发现存在此类缺陷的应用程序,否则不应使用。启用该选项会导致带宽和 CPU 使用率上升,在高延迟环境中可能显著降低性能。 参见:"option http-buffer-request" **`option http-pretend-keepalive`** ```haproxy option http-pretend-keepalive no option http-pretend-keepalive ``` 定义 HAProxy 是否向服务器通告 HTTP/1.x 连接的保持连接状态。 可以用于以下上下文:http 可出现在以下段中:defaults \| frontend \| listen \| backend yes \| no \| yes \| yes 参数:无 当启用 "option http-server-close" 或 "option httpclose" 时,HAProxy 会在转发至服务器的 HTTP/1.x 请求中添加 "Connection: close" 头。不幸的是,当某些服务器检测到该头时,会自动停止对长度未知的响应使用分块编码,而这一行为与实际无关。结果是,客户端或缓存可能接收到不完整的响应却未察觉,误认为响应已完整。 通过设置 "option http-pretend-keepalive",HAProxy 会令服务器误以为连接将保持活跃。服务器因此不会回退到上述异常的非期望状态。当 HAProxy 收到完整的响应后,将关闭与服务器的连接,其行为与启用 "option httpclose" 时一致。这样,客户端可获得正常的响应,且服务器端的连接得以正确关闭。 建议默认情况下不要启用此选项,因为大多数服务器在收到最后一个数据包后会更高效地自行关闭连接,并略微提前释放其缓冲区。此外,网络中增加的数据包可能会略微降低整体峰值性能。然而需要注意的是,启用此选项后,HAProxy 需要完成的工作量会略微减少。因此,如果 HAProxy 是整个架构中的性能瓶颈,启用此选项可能节省少量 CPU 周期。 该选项可在后端和 listen 段中设置。在前端段中使用将被忽略,并在启动时报告警告。此选项与后端相关,因此在前端设置并无实际意义。 如果该选项在“defaults”段中已启用,可以在特定实例中通过在其前添加“no”关键字来禁用。 另请参见:“option httpclose”、“option http-server-close” 和 “option http-keep-alive” **`option http-restrict-req-hdr-names { preserve | delete | reject }`** ```haproxy option http-restrict-req-hdr-names { preserve | delete | reject } ``` 设置 HAProxy 对包含非 "[a-zA-Z0-9-]" 字符集字符的 HTTP 请求头名称的处理策略 可以用于以下上下文:http 可出现在以下段中:defaults \| frontend \| listen \| backend yes \| yes \| yes \| yes 参数: ```text preserve disable the filtering. It is the default mode for HTTP proxies with no FastCGI application configured. delete remove request headers with a name containing a character outside the "[a-zA-Z0-9-]" charset. It is the default mode for HTTP backends with a configured FastCGI application. reject reject the request with a 403-Forbidden response if it contains a header name with a character outside the "[a-zA-Z0-9-]" charset. ``` 此选项可用于限制请求头名称仅包含字母、数字和连字符字符([A-Za-z0-9-])。在与不遵循 HTTP 协议的服务器互操作时,此限制可能是必须的,因为这些服务器无法正确处理头名称中的某些字符。对于 FastCGI 应用程序而言,此限制也可能为必须,因为头名称中所有非字母数字字符均会被下划线替换('\_')。因此,很容易混淆头名称并绕过某些规则。例如,“X-Forwarded-For” 和 "X_Forwarded-For" 头均会被转换为 "HTTP_X_FORWARDED_FOR"。 请注意,此选项按代理逐个评估,且在完成 http-request 规则评估之后进行。 **`option http-server-close`** ```haproxy option http-server-close no option http-server-close ``` 在服务器端启用或禁用 HTTP/1.x 连接关闭 可以用于以下上下文:http 可出现在以下段中:defaults \| frontend \| listen \| backend yes \| yes \| yes \| yes 参数:无 默认情况下,HAProxy 以持久连接模式运行,针对持久的 HTTP/1.x 连接:对于每个连接,HAProxy 会处理每个请求和响应,并在两端保持连接空闲。可通过多个选项更改此模式,例如“option http-server-close”或“option httpclose”。设置“option http-server-close”可在服务器端启用 HTTP connection-close 模式,同时保留客户端侧支持 HTTP 持久连接和流水线化的能力。该模式可实现客户端侧(慢速网络)最低延迟,并在服务器端实现最快会话复用,以节省服务器资源,与“option httpclose”效果类似。此外,只要服务器符合 RFC7230 的要求,该模式还允许非持久连接能力的服务器以持久连接模式向客户端提供服务。请注意,部分服务器在收到请求中的“Connection: close”时,可能并不完全符合这些要求。其结果是持久连接将永远无法使用。一种解决方法是启用“option http-pretend-keepalive”。 目前,日志不会标明请求是否来自同一会话。日志中报告的接受时间对应于前一个请求的结束时间,请求时间对应于等待新请求所花费的时间。若未设置,持久连接的请求时间仍受 "timeout http-keep-alive" 或 "timeout http-request" 定义的超时限制。 该选项可在前端和后端中设置。若持有连接的前端或后端中至少有一个启用了此选项,则该选项生效。启用后将禁用并替换任何先前配置的“option httpclose”或“option http-keep-alive”。请查阅 [第 4 节](/zh/docs/haproxy/proxies/)(“代理”)了解当前端与后端选项不同时,此选项如何与其他选项协同工作。 如果该选项在“defaults”段中已启用,可以在特定实例中通过在其前添加“no”关键字来禁用。 另请参见:“option httpclose”、“option http-pretend-keepalive” 和 “option http-keep-alive”。 **`option http-use-proxy-header`** ```haproxy option http-use-proxy-header no option http-use-proxy-header ``` 使用非标准的 Proxy-Connection 头代替 Connection 头 可以用于以下上下文:http 可出现在以下段中:defaults \| frontend \| listen \| backend yes \| yes \| yes \| no 参数:无 根据 RFC7230 明确规定,HTTP/1.1 代理必须使用 Connection 头来表明其希望维持持久连接或非持久连接。然而,浏览器和代理在代理连接中均忽略该头,并改用未公开、非标准的 Proxy-Connection 头。当尝试在浏览器与此类代理之间部署负载均衡器时,问题便随之产生,因为 HAProxy 所理解的行为与客户端和代理之间所达成的共识存在差异。 通过在前端中设置此选项,HAProxy 可在检测到代理请求时自动切换至使用该非标准头。此处定义的代理请求是指 URI 既不以 '/' 也不以 '\*' 开头的请求。此选项与 HTTP 隧道模式不兼容。请注意,该选项只能在前端中指定,并将影响请求的整个生命周期。 此外,当设置此选项时,若请求需要认证,且该请求本身是通过代理转发的,则会自动切换为使用代理认证头。这使得可在现有代理前端检查或强制执行认证。 此选项通常不应使用,仅在代理前端使用时例外。 另请参见:“option httpclose” 和 “option http-server-close”。 **`option httpchk`** ```haproxy option httpchk option httpchk option httpchk option httpchk option httpchk ``` 启用 HTTP 协议检查服务器健康状态 可用于以下上下文:tcp、http 可出现在以下段中:defaults \| frontend \| listen \| backend yes \| no \| yes \| yes 参数: ```text is the optional HTTP method used with the requests. When not set, the "OPTIONS" method is used, as it generally requires low server processing and is easy to filter out from the logs. Any method may be used, though it is not recommended to invent non-standard ones. is the URI referenced in the HTTP requests. It defaults to " / " which is accessible by default on almost any server, but may be changed to any other URI. Query strings are permitted. is the optional HTTP version string. It defaults to "HTTP/1.0" but some servers might behave incorrectly in HTTP 1.0, so turning it to HTTP/1.1 may sometimes help. Note that the Host field is mandatory in HTTP/1.1. is the optional HTTP Host header value. It is not set by default. It is a log-format string. ``` 默认情况下,服务器健康检查仅包含尝试建立 TCP 连接。当指定 "option httpchk" 时,在建立 TCP 连接后会发送完整的 HTTP 请求,响应码为 2xx 或 3xx 被视为有效,而所有其他响应均表示服务器故障,包括无任何响应的情况。 与 "http-check" 指令结合使用时,可自定义 HTTP 健康检查期间发送的请求,或配置对响应的匹配规则。也可配置 send/expect 序列,方式与 TCP 健康检查中的 "tcp-check" 指令相同。 默认情况下,服务器配置用于打开连接以执行 HTTP 健康检查。也可通过使用 "http-check connect" 规则覆盖服务器参数。 `httpchk` 选项并不要求必须使用 HTTP 后端,它同样适用于普通的 TCP 后端。这在使用 inetd 守护进程绑定到特定端口的简单脚本检测时尤为有用。然而,它始终内部依赖 HTX 多路复用器。因此,这意味着请求格式化和响应解析将严格遵循规范。 示例: ```shell # 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 http-check send hdr Host www server apache1 192.168.1.1:443 check port 80 ``` 另请参见:`option ssl-hello-chk`、`option smtpchk`、`option mysql-check`、`option pgsql-check`、`http-check` 以及 `check`、`port` 和 `inter` 服务器选项。 **`option httpclose`** ```haproxy option httpclose no option httpclose ``` 启用或禁用 HTTP/1.x 连接关闭 可以用于以下上下文:http 可出现在以下段中:defaults \| frontend \| listen \| backend yes \| yes \| yes \| yes 参数:无 默认情况下,HAProxy 以持久连接模式运行,针对持久的 HTTP/1.x 连接:每个连接在处理完每个请求和响应后,会在两端保持空闲状态。可通过多个选项更改此模式,例如 "option http-server-close" 或 "option httpclose"。 若设置 "option httpclose",HAProxy 将根据该选项的设置位置关闭客户端或服务器连接。前端用于客户端连接,后端用于服务器连接。若在监听器上设置该选项,则同时作用于客户端和服务器连接。HAProxy 会检查每个方向是否已设置 "Connection: close" 头,若缺失则添加。 此选项还可与 "option http-pretend-keepalive" 一同使用,该选项将禁用发送 "Connection: close" 请求头,但接收完整响应后仍会关闭连接。 它会禁用并替换任何先前配置的 "option http-server-close" 或 "option http-keep-alive"。 如果该选项在“defaults”段中已启用,可以在特定实例中通过在其前添加“no”关键字来禁用。 另请参见:"option http-server-close"。 **`option httplog [ clf ]`** ```haproxy option httplog [ clf ] ``` 启用 HTTP 请求、流状态和计时器的日志记录 可以用于以下上下文:http 可出现在以下段中:defaults \| frontend \| listen \| backend yes \| yes \| yes \| no 参数: ```text clf if the "clf" argument is added, then the output format will be the CLF format instead of HAProxy's default HTTP format. You can use this when you need to feed HAProxy's logs through a specific log analyzer which only support the CLF format and which is not extensible. ``` 默认情况下,日志输出格式非常简陋,仅包含源地址和目标地址以及实例名称。通过指定 "option httplog",每行日志将变为更丰富的格式,包括但不限于:HTTP 请求、连接计时器、流状态、连接数量、捕获的头字段和 Cookie、前端、后端及服务器名称,当然还包括源地址和端口。 仅指定 "option httplog" 时,将自动清除默认设置的 'clf' 模式。 "option httplog" 会覆盖之前设置的 "log-format" 指令。 另请参阅 [第 8 节](/zh/docs/haproxy/configuration-logging/) 中关于日志记录的内容。 **`option httpslog`** ```haproxy option httpslog ``` 启用 HTTPS 请求、流状态及计时器的日志记录 可以用于以下上下文:http 可出现在以下段中:defaults \| frontend \| listen \| backend yes \| yes \| yes \| no 默认情况下,日志输出格式非常简陋,仅包含源地址和目标地址以及实例名称。通过指定 "option httpslog",每行日志将变为更丰富的格式,包括但不限于:HTTP 请求、连接计时器、流状态、连接数量、捕获的头和 Cookie、前端、后端和服务器名称、SSL 证书验证状态和 SSL 握手状态,以及当然的源地址和端口。 "option httpslog" 会覆盖之前所有的 "log-format" 指令。 另请参阅 [第 8 节](/zh/docs/haproxy/configuration-logging/) 中关于日志记录的内容。 **`option idle-close-on-response`** ```haproxy option idle-close-on-response no option idle-close-on-response ``` 如果正在进行软停止,则避免关闭空闲的前端连接 可以用于以下上下文:http 可出现在以下段中:defaults \| frontend \| listen \| backend yes \| yes \| yes \| no 参数:无 默认情况下,软停止期间空闲连接将被关闭。在某些环境中,客户端与代理之间可能已建立一些空闲连接,以便稍后发送请求。如果未对写入错误进行适当的重试,这可能导致 HAProxy 重载时出现错误。尽管正确的实现应在连接或写入错误时重试,但此选项的引入是为了支持与 2.4 版本之前 HAProxy 的向后兼容性。事实上,在 2.4 版本之前,HAProxy 会在关闭连接前等待最后一个请求和响应,并添加 "Connection: close" 头,从而通知客户端该连接不可重用。 在实际案例中,此行为曾在 AWS 环境下观察到,即在 HAProxy 前端部署 ALB 时出现。最终结果为 ALB 在 HAProxy 重载期间返回 502 错误。 请注意,使用此选项可能导致连接空闲时间过长时旧进程数量增加。在频繁重载的情况下,可能需要相应调整客户端超时设置和/或“hard-stop-after”参数。 另请参阅:“timeout client”、“timeout client-fin”、“timeout http-request”、“hard-stop-after” **`option independent-streams`** ```haproxy option independent-streams no option independent-streams ``` 启用或禁用双向独立超时处理 可用于以下上下文:tcp、http 可出现在以下段中:defaults \| frontend \| listen \| backend yes \| yes \| yes \| yes 参数:无 默认情况下,当通过套接字发送数据时,该套接字的写超时和读超时都会被刷新,因为我们认为该套接字存在活动,且没有其他方式判断是否应接收数据。 当大多数应用程序均期望此默认行为时,仍存在一种情形下希望禁用该行为,仅在有传入数据时才刷新读取超时。这种情况常见于超时时间较长且交换数据量较小的流,例如 telnet 会话。若服务器突然消失,输出数据会累积在系统的套接字缓冲区中,两个超时均会被正确刷新,但无法得知服务器是否已无法接收这些数据,因此不会触发超时。然而,当底层协议始终回显已发送的数据时,仅通过读取超时即可自行检测该问题。请注意,该问题不会出现在更冗余的协议中,因为数据不会在套接字缓冲区中长时间累积。 当此选项在前端设置时,将禁用向客户端发送数据时的读取超时更新。此情况可能用途有限。当此选项在后端设置时,将禁用向服务器发送数据时的读取超时更新。此举通常会导致慢速链路上的大规模 HTTP 上传失败,因此应谨慎使用。 另请参阅:“timeout client”、“timeout server” 和 “timeout tunnel” **`option ldap-check`** ```haproxy option ldap-check ``` 使用 LDAPv3 健康检查测试服务器 可以用于以下上下文:tcp 可出现在以下段中:defaults \| frontend \| listen \| backend yes \| no \| yes \| yes 参数:无 可以测试服务器是否正确使用 LDAPv3 协议,而不仅仅是测试其是否接受 TCP 连接。启用此选项后,会向服务器发送 LDAPv3 匿名简单绑定消息,并分析响应以确认是否收到 LDAPv3 绑定响应消息。 仅当 LDAP 响应包含成功 resultCode()时,服务器才被视为有效。 绑定请求的日志记录取决于服务器,具体配置方法请参阅相关文档。 示例: ```text option ldap-check ``` 另请参见:"option httpchk" **`option log-health-checks`** ```haproxy option log-health-checks no option log-health-checks ``` 启用或禁用健康检查状态更新的日志记录 可用于以下上下文:tcp、http、log 可出现在以下段中:defaults \| frontend \| listen \| backend yes \| no \| yes \| yes 参数:无 默认情况下,当服务器处于 UP 状态时,会记录失败的健康检查;当服务器处于 DOWN 状态时,会记录成功的健康检查,因此额外信息的记录量有限。 当启用此选项时,健康检查状态或服务器健康状况的任何变化都将被记录,从而能够知晓某服务器在崩溃前是否曾间歇性地检查失败,或确切地了解其何时未能响应有效的 HTTP 状态,何时端口开始拒绝连接,以及何时服务器完全停止响应。 请注意,由健康检查以外的原因引起的状态变更(例如通过 CLI 执行的启用/禁用操作)不会被此选项记录。 另请参阅:“option httpchk”、“option ldap-check”、“option mysql-check”、“option pgsql-check”、“option redis-check”、“option smtpchk”、“option tcp-check”、“log”以及 [第 8 节](/zh/docs/haproxy/configuration-logging/) 关于日志记录的内容。 **`option log-separate-errors`** ```haproxy option log-separate-errors no option log-separate-errors ``` 更改非完全成功连接的日志级别 可用于以下上下文:tcp、http 可出现在以下段中:defaults \| frontend \| listen \| backend yes \| yes \| yes \| no 参数:无 有时在日志中查找错误并不容易。此选项可提升包含潜在重要信息的日志级别,例如错误、超时、重试、重分派或 HTTP 状态码 5xx。日志级别将从“info”提升至“err”。这使得大多数 syslog 守护进程能够将这些日志单独记录到不同的文件中。请注意,不要从原始文件中移除这些日志,否则将丢失顺序信息,而顺序信息提供了非常重要的上下文。 使用此选项,处理每秒数千个连接的大型站点可将正常流量日志记录至循环缓冲区,仅归档较小的错误日志。 另请参阅:“log”、“dontlognull”、“dontlog-normal”以及 [第 8 节](/zh/docs/haproxy/configuration-logging/) 中关于日志记录的内容。 **`option logasap`** ```haproxy option logasap no option logasap ``` 启用或禁用早期日志记录。 可用于以下上下文:tcp、http 可出现在以下段中:defaults \| frontend \| listen \| backend yes \| yes \| yes \| no 参数:无 默认情况下,当日志格式别名和样本提取项在日志格式字符串定义中全部返回值,或流终止时,将输出日志。这使得内置日志格式字符串能够计入传输时间,或日志消息中的字节数。 当处理长连接(如大文件传输或 RDP)时,请求或连接在日志中出现可能需要较长时间。使用 "option logasap" 选项后,日志消息将在 TCP 模式下服务器连接建立时,或 HTTP 模式下服务器发送完整头信息时立即生成。日志中缺失的信息包括总字节数,该值仅反映消息生成前已传输的数据量,以及总时间,该值未计入连接剩余生命周期或传输时间。对于 HTTP 情况,建议捕获 Content-Length 响应头,以便日志至少能指示预期传输的字节数。 示例: ```text listen http_proxy 0.0.0.0:80 mode http option httplog option logasap log 192.168.2.200 local3 ``` ```text >>> Feb 6 12:14:14 localhost \ haproxy[14389]: 10.0.1.2:33317 [06/Feb/2009:12:14:14.655] http-in \ static/srv1 9/10/7/14/+30 200 +243 - - ---- 3/1/1/1/0 1/0 \ "GET /image.iso HTTP/1.0" ``` 参见: "option httplog"、"capture response header",以及 [section 8](/zh/docs/haproxy/configuration-logging/) 关于日志记录的内容。 **`option mysql-check [ user [ { post-41 | pre-41 | post-80 } ] ]`** ```haproxy option mysql-check [ user [ { post-41 | pre-41 | post-80 } ] ] ``` 使用 MySQL 健康检查对服务器进行测试 可以用于以下上下文:tcp 可出现在以下段中:defaults \| frontend \| listen \| backend yes \| no \| yes \| yes 参数: ```text This is the username which will be used when connecting to MySQL server. post-41 Send post v4.1 client compatible checks (the default) pre-41 Send pre v4.1 client compatible checks post-80 Send post v8.0 client compatible checks with CLIENT_PLUGIN_AUTH capability set and mysql_native_password as the authentication plugin. Use this option when connecting to MySQL 8.0+ servers where the health check user is created with mysql_native_password authentication. Example: CREATE USER 'haproxy'@'%' IDENTIFIED WITH mysql_native_password BY ''; ``` 若指定用户名,检查过程将发送两个 MySQL 数据包:一个客户端认证数据包和一个 QUIT 数据包,以正确关闭 MySQL 会话。随后,解析 MySQL 握手初始化数据包和/或错误数据包。这是一种基础但实用的测试,不会在服务器端产生错误或中断连接。然而,该测试要求存在一个未锁定且无密码的授权用户。要在 MySQL 中创建一个基本的受限用户并可选地设置资源限制: ```text CREATE USER ''@'' /*!50701 WITH MAX_QUERIES_PER_HOUR 1 MAX_UPDATES_PER_HOUR 0 */ /*M!100201 MAX_STATEMENT_TIME 0.0001 */; ``` 如果不指定用户名(该做法已弃用且不推荐),检查仅包括解析 MySQL 握手初始化数据包或错误数据包,此模式下不会发送任何内容。有报告指出,若检查频率过高和/或流量不足,可能导致锁定。实际上,在此情况下,需检查 MySQL "max_connect_errors" 值,即如果在前一次连接中断后,服务器在少于 MySQL "max_connect_errors" 次尝试内成功建立连接,则该主机的错误计数将被清零。若 HAProxy 服务器被阻塞,“FLUSH HOSTS” 语句是解除阻塞的唯一方法。 请注意,这不会检查数据库是否存在或数据库一致性。如需执行此类检查,可以使用 xinetd 等外部检查工具。 该检查要求 MySQL 版本 ≥ 3.22,对于较旧版本,请使用 TCP 检查。 通常情况下,传入的 MySQL 服务器需要看到客户端的 IP 地址,以实现多种用途,包括 IP 权限匹配和连接日志记录。在可能的情况下,建议在通过 "source" 关键字的 "usesrc" 参数连接服务器时,对客户端 IP 地址进行伪装,这需要透明代理功能已编译启用,并且 MySQL 服务器需通过运行 HAProxy 的主机来路由客户端连接。 另请参见:"option httpchk" **`option nolinger`** ```haproxy option nolinger no option nolinger ``` 启用或禁用会话关闭后立即清理资源 可用于以下上下文:tcp、http、log 可出现在以下段中:defaults \| frontend \| listen \| backend yes \| yes \| yes \| yes 参数:无 当客户端或服务器以非正常方式中止连接(例如,物理断开连接)时,会话超时将被触发,会话随之关闭。但该会话将在系统中保持 FIN_WAIT1 状态一段时间,占用部分资源,并可能限制建立新连接的能力。 当发生此情况时,可以启用“option nolinger”选项,强制系统在关闭连接时立即清除套接字中待处理的数据。此时会发出 TCP RST,待处理数据被截断,会话将立即从系统的表中清除。对客户端而言,通常可见的效果是:若关闭操作发生在最后一个数据块时(例如重定向或错误响应),响应数据会被截断。在服务器端,当通过隧道转发时,若客户端中断连接,该选项有助于立即释放源端口。两种情况下均会发出 TCP 重置,由于会话被立即销毁,因此不会发生重传。在丢包率较高的网络中,这可能加剧问题,尤其是在丢包侧存在防火墙时,因为防火墙可能接收到并处理该重置(从而清除其会话状态),并阻止该会话的后续流量,包括来自另一侧的重传数据。因此,若另一侧未收到该重置,将永远无法再次接收 RST,而防火墙可能会记录大量被阻断的数据包。 出于上述所有原因,强烈建议不要使用此选项,除非在万不得已的情况下作为最后手段。在大多数场景中,使用 "client-fin" 或 "server-fin" 超时可实现类似效果,且行为更加可靠。在 Linux 上,还可选择使用 "tcp-ut" 绑定或服务器设置。 该选项可在前端和后端中使用,具体取决于其所需的位置。 在前端使用以处理客户端,在后端使用以处理服务器。 尽管该选项在“defaults”段中技术上受支持,但应避免在此处使用,以免意外传播至本不应使用该选项的段,从而引发问题。 如果该选项在“defaults”段中已启用,可以在特定实例中通过在其前添加“no”关键字来禁用。 另请参见:“timeout client-fin”、“timeout server-fin”、“tcp-ut” 绑定或服务器关键字。 **`option originalto [ except ] [ header ]`** ```haproxy option originalto [ except ] [ header ] ``` 启用向发送至服务器的请求中插入 X-Original-To 头 可以用于以下上下文:http 可出现在以下段中:defaults \| frontend \| listen \| backend yes \| yes \| yes \| yes 参数: ```text is an optional argument used to disable this option for sources matching an optional argument to specify a different "X-Original-To" header name. ``` 由于 HAProxy 可以工作在透明模式下,客户端的每个请求都可能被重定向至代理,而 HAProxy 本身可将每个请求转发至复杂的 SQUID 环境,此时 SO_ORIGINAL_DST 的目标主机将丢失。当需要基于目标 IP 地址设置访问规则时,这种情况会带来困扰。为解决此问题,HAProxy 可向发送至服务器的所有请求添加新的 HTTP 头 "X-Original-To"。该头包含表示原始目标 IP 地址的值。必须配置为仅使用该头的最后一次出现。请注意,仅应使用该头的最后一次出现,因为客户端可能已携带了该头。 关键字 "header" 可用于指定一个不同的头名称,以替换默认的 "X-Original-To"。当可能已从其他应用接收了 "X-Original-To" 头,且需要保留该头时,此功能非常有用。此外,若后端服务器不使用 "X-Original-To" 头,而需要其他头名称时,也可使用此功能。 有时,同一个 HAProxy 实例可能同时用于直接客户端访问和反向代理访问(例如,当使用 SSL 反向代理解密 HTTPS 流量时)。可以通过添加 "except" 关键字并指定网络地址,禁用对已知目标地址或网络的头字段添加。在此情况下,任何与该网络匹配的目标 IP 都不会触发该头字段的添加。常见用法包括私有网络或 127.0.0.1。支持 IPv4 和 IPv6。 该选项可在前端或后端中指定。若其中至少一个使用了该选项,将添加该头。请注意,若前后端均定义了该头的子参数,后端的设置将优先于前端。 示例: ```shell # Original Destination address frontend www mode http option originalto except 127.0.0.1 # Those servers want the IP Address in X-Client-Dst backend www mode http option originalto header X-Client-Dst ``` 另请参见:“option httpclose”、“option http-server-close”。 **`option persist`** ```haproxy option persist no option persist ``` 启用或禁用对已关闭服务器的强制持久化 可用于以下上下文:tcp、http 可出现在以下段中:defaults \| frontend \| listen \| backend yes \| no \| yes \| yes 参数:无 当 HTTP 请求到达一个包含引用已失效服务器的 cookie 的后端时,默认情况下会将其重分派至另一台服务器。若确实需要,可使用“option persist”强制请求首先发送至该已失效服务器。常见应用场景为服务器处于极端负载状态,导致其频繁波动。在此情况下,用户仍会被引导至其会话初始连接的服务器,以期获得正确服务。建议与该选项配合使用“option redispatch”,以便在无法连接至该服务器(服务器已彻底失效)时,最终将客户端重定向至另一台有效服务器。 如果该选项在“defaults”段中已启用,可以在特定实例中通过在其前添加“no”关键字来禁用。 另请参见:“option redispatch”、“retries”、“force-persist” **`option pgsql-check user `** ```haproxy option pgsql-check user ``` 使用 PostgreSQL 健康检查对服务器进行测试 可以用于以下上下文:tcp 可出现在以下段中:defaults \| frontend \| listen \| backend yes \| no \| yes \| yes 参数: ```text This is the username which will be used when connecting to PostgreSQL server. ``` 该检查发送一个 PostgreSQL StartupMessage,并等待收到 Authentication request 或 ErrorResponse 消息。这是一种基础但实用的测试,不会在服务器端产生错误或中断连接。此检查与 "mysql-check" 完全相同。 另请参见:"option httpchk" **`option prefer-last-server`** ```haproxy option prefer-last-server no option prefer-last-server ``` 允许多个负载均衡的请求保持在同一个服务器上 可用于以下上下文:tcp、http 可出现在以下段中:defaults \| frontend \| listen \| backend yes \| no \| yes \| yes 参数:无 当所使用的负载均衡算法不具备确定性时,若此前请求已发送至 HAProxy 仍保持连接的服务器,则在同一会话中尽可能将后续请求也发送至同一服务器,有时是可取的。请注意,这与会话保持不同,因为此处仅表示一种偏好,HAProxy 会尝试应用该偏好,但不提供任何形式的保证。此功能的实际用途在于对服务器发起的持久连接。启用该选项后,HAProxy 将尝试复用与服务器关联的现有连接,而非重新均衡至另一服务器,从而避免关闭连接。该机制对静态文件服务器具有实际意义。与哈希算法结合使用时,此选项意义不大。请注意,当负载均衡算法不具备确定性时,HAProxy 已自动尝试保持与返回 401 响应的服务器或返回 407 响应的代理(需认证)的连接。在处理存在缺陷的 NTLM 认证挑战时,此行为为强制要求,且对排查部分异常应用具有显著帮助。在这些环境中,启用 prefer-last-server 选项也可能有益,以避免每次响应后重新分配流量。 本文档中明确指出,哪些负载均衡算法属于确定性算法较为有用。 确定性算法在可用服务器集合未发生变化的前提下,对给定客户端数据始终选择相同的服务器。通常情况下,确定性算法通过哈希或查找传入请求中的信息来选择目标服务器。然而,这并非总是成立;例如,“static-rr”算法也可视为确定性算法,因为服务器选择基于服务器的静态权重,使得选择结果可预测。“sticky”算法为返回客户端提供确定性路由。 对于非确定性算法,这些算法根据动态服务器状态或简单轮询选择服务器,因此两个连续的请求无法保证落在同一台服务器上。option prefer-last-server 专门为此类算法设计。roundrobin 和 leastconn 即为这类算法的示例。 如果该选项在“defaults”段中已启用,可以在特定实例中通过在其前添加“no”关键字来禁用。 另请参见:"option http-keep-alive" **`option redispatch`** ```haproxy option redispatch option redispatch no option redispatch ``` 在连接失败时启用或禁用会话重分配 可用于以下上下文:tcp、http 可出现在以下段中:defaults \| frontend \| listen \| backend yes \| no \| yes \| yes 参数: ```text The optional integer value that controls how often redispatches occur when retrying connections. Positive value P indicates a redispatch is desired on every Pth retry, and negative value N indicate a redispatch is desired on the Nth retry prior to the last retry. For example, the default of -1 preserves the historical behavior of redispatching on the last retry, a positive value of 1 would indicate a redispatch on every retry, and a positive value of 3 would indicate a redispatch on every third retry. You can disable redispatches with a value of 0. ``` 在 HTTP 模式下,如果客户端通过 Cookie 指定的服务器宕机,客户端可能会持续连接到该服务器,例如使用 "option persist" 或 "force-persist" 时,因为客户端无法清除 Cookie,将无法再访问服务。 启用 "option redispatch" 可使代理打破基于 cookie 或一致性哈希的持久性,将请求重新分派至可用的服务器。 从可用服务器列表的子集中选择活跃服务器。未处于宕机或维护状态(即未进行健康检查,或已被检查为“正常”)的活跃服务器,按以下顺序进行选择: ```text 1. Any active, non-backup server, if any, or, 2. If the "allbackups" option is not set, the first backup server in the list, or 3. If the "allbackups" option is set, any backup server. ``` 重试时,HAProxy 会尝试选择除上一次以外的另一台服务器。新服务器将从当前服务器列表中选取。 有时,如果在重试期间更新了列表(例如,发生大量重试且耗时超过检查服务器是否已宕机所需的时间,导致将其从列表中移除并回退到备用服务器列表),连接仍可能被重定向至备用服务器。 它还允许在发生多次连接失败时,重试连接到另一台服务器。当然,这要求将“retries”设置为非零值。 如果该选项在“defaults”段中已启用,可以在特定实例中通过在其前添加“no”关键字来禁用。 另请参阅: "option persist"、"force-persist"、"retries" **`option redis-check`** ```haproxy option redis-check ``` 使用 Redis 健康检查对服务器进行测试 可以用于以下上下文:tcp 可出现在以下段中:defaults \| frontend \| listen \| backend yes \| no \| yes \| yes 参数:无 可以测试服务器是否正确使用 REDIS 协议,而不仅仅是测试其是否接受 TCP 连接。启用此选项后,HAProxy 会向服务器发送 PING REDIS 命令,并分析响应以查找 "+PONG" 响应消息。 示例: ```text option redis-check ``` 另请参见:"option httpchk"、"option tcp-check"、"tcp-check expect" **`option smtpchk`** ```haproxy option smtpchk option smtpchk ``` 使用 SMTP 健康检查测试服务器 可以用于以下上下文:tcp 可出现在以下段中:defaults \| frontend \| listen \| backend yes \| no \| yes \| yes 参数: ```text is an optional argument. It is the "hello" command to use. It can be either "HELO" (for SMTP) or "EHLO" (for ESMTP). All other values will be turned into the default command ("HELO"). is the domain name to present to the server. It may only be specified (and is mandatory) if the hello command has been specified. By default, "localhost" is used. ``` 当设置 "option smtpchk" 时,健康检查将包含 TCP 连接后跟一个 SMTP 命令。默认情况下,该命令为 "HELO localhost"。服务器返回的响应码将被分析,仅以 "2" 开头的响应码被视为有效。所有其他响应,包括无响应的情况,均视为错误,并表示服务器已失效。 此测试适用于 SMTP 服务器或中继。根据请求的不同,某些服务器可能不会记录每次连接尝试,因此建议进行试验以优化行为。使用 telnet 连接端口 25 通常比调整配置更简便。 大多数情况下,传入的 SMTP 服务器需要查看客户端的 IP 地址,以实现多种目的,包括垃圾邮件过滤、防伪造和日志记录。在可能的情况下,建议在使用 "source" 关键字的 "usesrc" 参数连接服务器时,对客户端 IP 地址进行伪装,这需要编译时启用透明代理功能。 示例: ```text option smtpchk HELO mydomain.org ``` 另请参阅: "option httpchk"、"source" option socket-stats no option socket-stats 启用或禁用为每个套接字单独收集和提供统计信息。 可用于以下上下文:tcp、http 可出现在以下段中:defaults \| frontend \| listen \| backend yes \| yes \| yes \| no 参数:无 **`option splice-auto`** ```haproxy option splice-auto no option splice-auto ``` 启用或禁用套接字在两个方向上的自动内核加速 可用于以下上下文:tcp、http 可出现在以下段中:defaults \| frontend \| listen \| backend yes \| yes \| yes \| yes 参数:无 当在前端或后端启用此选项时,HAProxy 将自动评估是否可利用内核 TCP 拼接技术在客户端与服务器之间双向转发数据。HAProxy 使用启发式算法估算拼接是否可能提升性能。两个方向的处理相互独立。请注意,所采用的启发式算法并不激进,以避免拼接的过度使用。此选项要求在编译时启用拼接功能,并可通过全局选项 "nosplice" 全局禁用。由于拼接使用管道,因此使用该功能需确保有足够的空闲管道。 重要提示:基于内核的 TCP 拼接是 Linux 特有的功能,最早出现在内核 2.6.25 版本中。该功能通过在内核层面直接在套接字之间传输数据,无需将数据复制到用户空间,从而显著提升性能并节省 CPU 周期。由于早期实现存在缺陷,可能导致数据损坏或效率低下,因此该功能默认未启用,使用时应格外谨慎。尽管无法检测实现的正确性,但 2.6.29 版本是首个提供正确实现的版本。如有疑问,可使用全局配置项 "nosplice" 全局禁用拼接功能。 示例: ```text option splice-auto ``` 如果该选项在“defaults”段中已启用,可以在特定实例中通过在其前添加“no”关键字来禁用。 另请参阅:`option splice-request`、`option splice-response` 以及全局选项 `nosplice` 和 `maxpipes` **`option splice-request`** ```haproxy option splice-request no option splice-request ``` 启用或禁用请求的套接字自动内核加速 可用于以下上下文:tcp、http 可出现在以下段中:defaults \| frontend \| listen \| backend yes \| yes \| yes \| yes 参数:无 当在前端或后端启用此选项时,HAProxy 将尽可能使用内核 TCP 拼接技术,将客户端到服务器的数据直接转发。若无可用的管道资源,仍可能采用 recv/send 方式。此选项需在编译时启用拼接功能,且可通过全局选项 "nosplice" 全局禁用。由于拼接依赖管道,使用该功能要求系统具备足够的空闲管道资源。 请注意:有关使用限制,请参阅“option splice-auto”。 示例: ```text option splice-request ``` 如果该选项在“defaults”段中已启用,可以在特定实例中通过在其前添加“no”关键字来禁用。 另请参见:"option splice-auto"、"option splice-response" 以及全局选项 "nosplice" 和 "maxpipes" **`option splice-response`** ```haproxy option splice-response no option splice-response ``` 启用或禁用对响应的套接字自动进行内核加速 可用于以下上下文:tcp、http 可出现在以下段中:defaults \| frontend \| listen \| backend yes \| yes \| yes \| yes 参数:无 当在前端或后端启用此选项时,HAProxy 将尽可能使用内核 TCP 拼接技术,将数据从服务器转发至客户端。若无可用的管道资源,仍可能采用 recv/send 方式。此选项需在编译时启用拼接功能,且可通过全局选项 "nosplice" 全局禁用。由于拼接依赖管道,使用该功能要求系统具备足够的空闲管道资源。 请注意:有关使用限制,请参阅“option splice-auto”。 示例: ```text option splice-response ``` 如果该选项在“defaults”段中已启用,可以在特定实例中通过在其前添加“no”关键字来禁用。 另请参见:"option splice-auto"、"option splice-request" 以及全局选项 "nosplice" 和 "maxpipes" **`option spop-check`** ```haproxy option spop-check ``` 使用 SPOP 健康检查对服务器进行测试 可以用于以下上下文:tcp 可出现在以下段中:defaults \| frontend \| listen \| backend yes \| no \| yes \| yes 参数:无 可以测试服务器是否正确地使用 SPOP 协议,而不仅仅是测试其是否接受 TCP 连接。启用此选项后,HAProxy 与服务器之间将执行 HELLO 握手,随后分析响应以检查是否报告了错误。 示例: ```text option spop-check ``` 另请参见:"option httpchk" **`option srvtcpka`** ```haproxy option srvtcpka no option srvtcpka ``` 启用或禁用在服务器端发送 TCP keepalive 数据包 可用于以下上下文:tcp、http、log 可出现在以下段中:defaults \| frontend \| listen \| backend yes \| no \| yes \| yes 参数:无 当客户端与服务器之间存在防火墙或其他会话感知组件,且协议涉及长时间会话及较长空闲期(例如远程桌面)时,中间组件可能因会话空闲时间过长而决定终止该会话,从而带来风险。 启用套接字级别的 TCP 持久连接可使系统定期向连接的另一端发送数据包,从而保持连接处于活跃状态。持久连接探测之间的延迟由系统控制,且取决于操作系统及其调优参数。 必须理解,持久连接报文不会在应用层发出或接收,仅网络协议栈能够感知到它们。因此,即使代理的一端已使用持久连接来维持连接活跃,这些持久连接报文也不会被转发至代理的另一端。 请注意,这与 HTTP 持久连接无关。 使用选项 "srvtcpka" 可在连接的服务器端启用 TCP 持久连接探测,当 HAProxy 与服务器之间的会话超时被察觉时,此功能应能提供帮助。 如果该选项在“defaults”段中已启用,可以在特定实例中通过在其前添加“no”关键字来禁用。 另请参阅:"option clitcpka"、"option tcpka" **`option ssl-hello-chk`** ```haproxy option ssl-hello-chk ``` 使用 SSLv3 客户端问候消息进行服务器健康检查 可用于以下上下文:tcp、http 可出现在以下段中:defaults \| frontend \| listen \| backend yes \| no \| yes \| yes 参数:无 当通过 HAProxy 以 TCP 模式中继某些基于 SSL 的协议时,可以测试服务器是否正确地使用 SSL 通信,而不仅仅是测试其是否接受 TCP 连接。当设置 "option ssl-hello-chk" 时,连接建立后会向服务器发送一个纯 SSLv3 客户端问候消息,然后分析响应以查找 SSL 服务器问候消息。只有当响应中包含该服务器问候消息时,才认为服务器有效。 所有服务器均经过测试,确保其能正确响应 SSLv3 客户端握手消息,且大多数服务器甚至不会记录仅包含握手消息的请求,这一点值得肯定。 请注意,即使 HAProxy 未编译 SSL 支持,此健康检查仍可正常工作,因为它会伪造 SSL 消息。当 SSL 支持可用时,建议使用原生 SSL 健康检查,而非此方法。 另请参阅:“option httpchk”、“check-ssl” **`option tcp-check`** ```haproxy option tcp-check ``` 使用 tcp-check send/expect 序列执行健康检查 可用于以下上下文:tcp、http、log 可出现在以下段中:defaults \| frontend \| listen \| backend yes \| no \| yes \| yes 此健康检查方法旨在与“tcp-check”命令列表结合使用,以支持发送/期望类型的健康检查序列。 TCP 健康检查目前支持 4 种操作模式: - 无 "tcp-check" 指令:健康检查仅包含一次连接尝试,此为默认模式。 - "tcp-check send" or "tcp-check send-binary" only is mentioned: this is used to send a string along with a connection opening. With some protocols, it helps sending a "QUIT" message for example that prevents the server from logging a connection error for each health check. The check result will still be based on the ability to open the connection only. - "tcp-check expect" only is mentioned: this is used to test a banner. The connection is opened and HAProxy waits for the server to present some contents which must validate some rules. The check result will be based on the matching between the contents and the rules. This is suited for POP, IMAP, SMTP, FTP, SSH, TELNET. - both "tcp-check send" and "tcp-check expect" are mentioned: this is used to test a hello-type protocol. HAProxy sends a message, the server responds and its response is analyzed. the check result will be based on the matching between the response contents and the rules. This is often suited for protocols which require a binding or a request/response model. LDAP, MySQL, Redis and SSL are example of such protocols, though they already all have their dedicated checks with a deeper understanding of the respective protocols. In this mode, many questions may be sent and many answers may be analyzed. 第五种模式可用于在脚本的不同步骤中插入注释。 对于每个创建的 tcp-check 规则,可以添加一个 "comment" 指令,后接一个字符串。该字符串将在日志中以及调试模式下的 stderr 中输出。此功能有助于实现用户友好的错误报告。"comment" 指令为可选。 在执行健康检查期间,可通过使用 "tcp-check set-var" 操作,提供变量作用域以存储数据样本。可使用 "tcp-check unset-var" 释放这些变量。 示例: ```shell # perform a POP check (analyze only server's banner) option tcp-check tcp-check expect string +OK\ POP3\ ready comment POP\ protocol # perform an IMAP check (analyze only server's banner) option tcp-check tcp-check expect string *\ OK\ IMAP4\ ready comment IMAP\ protocol # look for the redis master server after ensuring it speaks well # redis protocol, then it exits properly. # (send a command then analyze the response 3 times) option tcp-check tcp-check comment PING\ phase tcp-check send PING\r\n tcp-check expect string +PONG tcp-check comment role\ check tcp-check send info\ replication\r\n tcp-check expect string role:master tcp-check comment QUIT\ phase tcp-check send QUIT\r\n tcp-check expect string +OK forge a HTTP request, then analyze the response (send many headers before analyzing) option tcp-check tcp-check comment forge\ and\ send\ HTTP\ request tcp-check send HEAD\ /\ HTTP/1.1\r\n tcp-check send Host:\ www.mydomain.com\r\n tcp-check send User-Agent:\ HAProxy\ tcpcheck\r\n tcp-check send \r\n tcp-check expect rstring HTTP/1\..\ (2..|3..) comment check\ HTTP\ response ``` 另请参见:“tcp-check connect”、“tcp-check expect” 和 “tcp-check send”。 **`option tcp-smart-accept`** ```haproxy option tcp-smart-accept no option tcp-smart-accept ``` 启用或禁用在连接建立过程中保存一个 ACK 数据包 可用于以下上下文:tcp、http 可出现在以下段中:defaults \| frontend \| listen \| backend yes \| yes \| yes \| no 参数:无 当 HTTP 连接请求到达时,系统会代表 HAProxy 进行确认,随后客户端立即发送请求,系统在通知 HAProxy 新连接的同时也对该请求进行确认。HAProxy 随后读取请求并发送响应。这意味着系统会额外发送一次 TCP ACK,而该 ACK 实际上是多余的,因为 HAProxy 完全可以在发送响应时一并确认该请求。 因此,在 HTTP 模式下,HAProxy 会自动请求系统在支持该功能的平台(目前至少包括 Linux)上避免发送此无用的 ACK。这不会造成任何问题,因为如果响应耗时超过预期,系统将在 40 毫秒后仍会发送该 ACK。 在复杂的网络故障排查会话中,可能需要禁用此优化,因为延迟确认(delayed ACKs)会使排查数据包延迟位置时更加复杂。此时可通过指定“no option tcp-smart-accept”恢复到正常行为。 也可以通过简单地指定“option tcp-smart-accept”来强制对非 HTTP 代理生效。例如,对于 SMTP 等某些服务,服务器会先发起通信,此时该选项可能具有实际意义。 建议避免在 defaults 段中强制设置此选项。如有疑问,可通过在该选项前添加 "default" 关键字将其恢复为自动值,或使用 "no" 关键字禁用该选项。 另请参见:"option tcp-smart-connect" **`option tcp-smart-connect`** ```haproxy option tcp-smart-connect no option tcp-smart-connect ``` 启用或禁用在连接过程中保存一个 ACK 数据包 可用于以下上下文:tcp、http 可出现在以下段中:defaults \| frontend \| listen \| backend yes \| no \| yes \| yes 参数:无 在某些系统(至少为 Linux)上,HAProxy 可以请求内核在收到连接请求时,不立即发送空的 ACK,而是直接发送缓冲区请求。此举可减少网络中一个数据包的传输,从而提升性能。对于某些服务器而言,此机制也具有实用性,因为它们能随连接建立立即获取请求数据。 当后端中设置 "option tcp-smart-connect" 时,此功能被启用。由于该功能会增加网络故障排查的复杂性,因此默认情况下未启用。 仅在客户端率先发起通信的协议(如 HTTP)中启用此功能才有意义。在其他情况下,若无数据可替代 ACK 发送,则发送正常的 ACK。 如果该选项在“defaults”段中已启用,可以在特定实例中通过在其前添加“no”关键字来禁用。 另请参见:"option tcp-smart-accept" **`option tcpka`** ```haproxy option tcpka ``` 启用或禁用在两端发送 TCP keepalive 数据包 可用于以下上下文:tcp、http、log 可出现在以下段中:defaults \| frontend \| listen \| backend yes \| yes \| yes \| yes 参数:无 当客户端与服务器之间存在防火墙或其他会话感知组件,且协议涉及长时间会话及较长空闲期(例如远程桌面)时,中间组件可能因会话空闲时间过长而决定终止该会话,从而带来风险。 启用套接字级别的 TCP 持久连接可使系统定期向连接的另一端发送数据包,从而保持连接处于活跃状态。持久连接探测之间的延迟由系统控制,且取决于操作系统及其调优参数。 必须理解,持久连接报文不会在应用层发出或接收,仅网络协议栈能够感知到它们。因此,即使代理的一端已使用持久连接来维持连接活跃,这些持久连接报文也不会被转发至代理的另一端。 请注意,这与 HTTP 持久连接无关。 启用选项 "tcpka" 可在连接的客户端和服务器两端均发送 TCP 持久连接探测。请注意,此选项仅在 "defaults" 或 "listen" 段中有效。若在前端中使用此选项,仅客户端会启用持久连接;若在后端中使用此选项,仅服务器端会启用持久连接。因此,强烈建议在配置跨前端和后端分布时,显式使用 "option clitcpka" 和 "option srvtcpka"。 另请参阅: "option clitcpka"、"option srvtcpka" **`option tcplog [clf]`** ```haproxy option tcplog [clf] ``` 启用 TCP 连接的高级日志记录,包括流状态和计时器信息 可用于以下上下文:tcp、http 可出现在以下段中:defaults \| frontend \| listen \| backend yes \| yes \| yes \| no 参数: ```text clf if the "clf" argument is added, then the output format will be the CLF format instead of HAProxy's default TCP format. You can use this when you need to feed HAProxy's logs through a specific log analyzer which only support the CLF format and which is not extensible. Since this expects an HTTP format some of the values have been pre set. The http request will show as TCP and the response code will show as 000. ``` 默认情况下,日志输出格式非常简陋,仅包含源地址和目标地址以及实例名称。通过指定“option tcplog”,每条日志行将变为更丰富的格式,包含但不限于连接计时器、流状态、连接数量、前端、后端和服务器名称,以及源地址和端口。该选项适用于纯 TCP 代理,以便确定是客户端还是服务器端断开连接或超时。对于常规 HTTP 代理,建议使用“option httplog”,其信息更为完整。 "option tcplog" 会覆盖之前所有的 "log-format" 指令。 另请参阅:“option httplog”,以及 [第 8 节](/zh/docs/haproxy/configuration-logging/) 关于日志记录的内容。 **`option transparent (deprecated)`** ```haproxy option transparent (deprecated) no option transparent (deprecated) ``` 启用客户端透明代理 可用于以下上下文:tcp、http 可出现在以下段中:defaults \| frontend \| listen \| backend yes \| no \| yes \| yes 参数:无 此选项的引入旨在为第 3 层负载均衡器提供第 7 层持久性。其原理是利用操作系统将来自远程地址的入站连接重定向至本地进程(此处为 HAProxy),并让该进程知晓最初请求的地址。启用此选项后,未携带 Cookie 的会话将被转发至入站请求的原始目标 IP 地址(该地址应与另一台设备的地址匹配),而携带 Cookie 的请求仍会被转发至相应的服务器。 请注意,与普遍认知相反,此选项并不会在建立连接时向服务器呈现客户端的 IP 地址。 从 3.3 版本开始,该选项已被弃用,因其曾存在多项内部技术限制。使用该选项将发出警告,如确需使用,可通过全局关键字 "expose-deprecated-directives" 避免警告。 正确做法是在地址 0.0.0.0 上声明一个服务器,该服务器将负责连接到预期的目标地址。服务器还将正确处理与目标服务器的空闲连接。 示例: ```shell # option transparent ## before 3.3 server transparent 0.0.0.0 ``` 另请参阅“source”关键字的“usesrc”参数,以及“bind”关键字的“transparent”选项。 option use-small-buffers [ queue \| l7-retries \| check ]* 为指定类别启用小缓冲区支持。 可用于以下上下文:tcp、http 可出现在以下段中:defaults \| frontend \| listen \| backend yes \| no \| yes \| yes 此选项可用于在不同位置启用小缓冲区支持,以节省内存。默认情况下,不带参数时,尽可能在所有可能的位置使用小缓冲区。否则,可将其限制为仅在以下位置启用: - queue:启用后,若连接被排队,将使用小缓冲区存储请求,前提是请求足够小。 - l7-retries:启用后,启用 L7 重试时将使用小缓冲区保存请求。 - check:启用后,健康检查请求将使用小缓冲区。 启用后,将使用小缓冲区,但仅在可行时。若数据过大,则自动改用常规缓冲区。小缓冲区的大小可通过 "tune.bufsize.small" 全局设置进行配置。 如果该选项在“defaults”段中已启用,可以在特定实例中通过在其前添加“no”关键字来禁用。 另请参见:tune.bufsize.small **`persist rdp-cookie`** ```haproxy persist rdp-cookie persist rdp-cookie() ``` 启用基于 RDP 会话 Cookie 的持久性 可以用于以下上下文:tcp 可出现在以下段中:defaults \| frontend \| listen \| backend yes \| no \| yes \| yes 参数: ```text is the optional name of the RDP cookie to check. If omitted, the default cookie name "msts" will be used. There currently is no valid reason to change this name. ``` 此语句启用基于 RDP Cookie 的会话保持功能。RDP Cookie 包含在已知服务器列表中定位服务器所需的所有信息。因此,当在后端中设置此选项时,请求将被分析;若发现 RDP Cookie,则对其进行解码。若解码结果匹配某个仍处于 UP 状态的已知服务器(或已设置 "option persist"),则连接将被转发至该服务器。 请注意,此配置仅在 TCP 后端中有效,但要使其生效,前端必须等待足够长的时间,以确保 RDP Cookie 已存在于请求缓冲区中。这与使用“rdp-cookie”负载均衡方法的要求相同。因此,强烈建议将所有配置项置于单一的“listen”段中。 此外,必须理解,仅当终端服务器配置为“令牌重定向模式”时,才会发出此 RDP 令牌,这意味着已禁用“IP 地址重定向”选项。 示例: ```text listen tse-farm bind:3389 # wait up to 5s for an RDP cookie in the request tcp-request inspect-delay 5s tcp-request content accept if RDP_COOKIE # apply RDP cookie persistence persist rdp-cookie # if server is unknown, let's balance on the same cookie. # alternatively, "balance leastconn" may be useful too. balance rdp-cookie server srv1 1.1.1.1:3389 server srv2 1.1.1.2:3389 ``` 参见: "balance rdp-cookie"、"tcp-request" 以及 "req.rdp_cookie" ACL。 **`quic-initial [ { if | unless } ]`** ```haproxy quic-initial [ { if | unless } ] ``` 对传入的 QUIC Initial 数据包执行一个动作。与 "tcp-request connection" 不同,该动作在任何连接元素实例化之前、SSL 握手启动和完成之前执行,因此在需要拒绝连接尝试时效率更高。 可以用于以下上下文:http 可出现在以下段中:defaults \| frontend \| listen \| backend yes(!) \| yes \| yes \| no 参数: ```text defines the action to perform if the condition applies. See below. is a standard layer4-only ACL-based condition (see section 7). However, QUIC initial rules are executed too early even for some layer4 sample fetch methods despite no configuration warning and may result in unspecified runtime behavior, although they will not crash. Consider that only internal samples and layer4 "src*" and "dst*" are considered as supported for now. ``` 此动作在 QUIC 数据包解析的早期阶段执行。因此,仅支持极少量的动作: - accept - dgram-drop - reject - send-retry **`rate-limit sessions `** ```haproxy rate-limit sessions ``` 在前端上设置每秒可接受的新会话数量限制 可用于以下上下文:tcp、http 可出现在以下段中:defaults \| frontend \| listen \| backend yes \| yes \| yes \| no 参数: ```text The parameter is an integer designating the maximum number of new sessions per second to accept on the frontend. ``` 当前端每秒新建会话数达到指定数量时,将停止接受新的连接,直至速率再次低于限制。在此期间,待处理的会话将保留在套接字的连接队列(系统缓冲区)中,HAProxy 甚至不会察觉到会话正在等待。在对高负载服务设置极低限制时,建议使用 "backlog" 关键字增加套接字的连接队列长度。 该功能在阻止基于连接的攻击或对脆弱服务器的服务滥用方面尤为高效。由于会话速率每毫秒测量一次,因此精度极高。此外,限制立即生效,无需任何延迟即可检测到阈值。 示例:将 SMTP 的连接速率限制为每秒最多 10 次 listen smtp mode tcp bind :25 rate-limit sessions 10 server smtp1 127.0.0.1:1025 请注意:当达到最大速率时,前端的状态不会改变,但如果启用了“socket-stats”选项,其套接字将在统计信息中显示为“WAITING”。 参见:`backlog` 关键字以及 "fe_sess_rate" ACL 条件。 **`redirect location [code ]