Writing Conditions

HAProxy can perform many types of actions on streams that pass through it. It is also possible to perform these actions under certain conditions only.

Write a condition

To form a condition, you can use the following syntax after the rule that it applies to:

<HAProxy action statement> if|unless [!]acl1 <AND|OR|or|'||'> [!]acl2 ...

– <HAProxy action statement> : the action you want to perform with HAProxy such as content switching, HTTP rewriting, denying, etc.

if or unless: how to validate the result of the ACL, as follows:

  • if : the condition is TRUE if the result of the ACLs is TRUE.
  • unless : the condition is TRUE if the result of the ACLs is FALSE

[!] (optional): to negate the result of an ACL

<acl1>, <acl2>: the name of the ACLs. (More information on ACLs)

AND, OR, or, ||: logical operators to apply between ACLs in order to form conditions:

  • if no operator is provided between two ACLs, then a logical AND is applied
  • AND: logical AND
  • OR, or, || : logical OR
The AND operator has precedence over the OR operators.

Examples of Conditions

  • Deny POST requests without content-length
acl missing_cl hdr_cnt(Content-length) eq 0
http-request deny if METH_POST missing_cl

http-request deny if METH_POST missing_cl

  • Deny HTTP requests to the “*” URL with HTTP methods other than “OPTIONS”
http-request deny if HTTP_URL_STAR !METH_OPTIONS
  • Deny both examples above at the same time:
acl missing_cl hdr_cnt(Content-length) eq 0
http-request deny if METH_POST missing_cl or HTTP_URL_STAR !METH_OPTIONS
  • Allow only requests for GET, POST, HEAD or OPTIONS:
http-request deny unless METH_GET or METH_POST or METH_OPTIONS
  • Select a different back end for requests to static contents on the www site and to every request on the img, video, download and ftp hosts:
acl url_static  path_beg         /static /images /img /css
acl url_static  path_end         .gif .png .jpg .css .js
acl host_www    hdr_beg(host) -i www
acl host_static hdr_beg(host) -i img. video. download. ftp.
# now use backend "static" for all static-only hosts, and for static urls
# of host "www". Use backend "www" for the rest.
use_backend static if host_static or host_www url_static
use_backend www    if host_www