Access Control Lists: path, headers, methods, status codes
Access Control Lists (ACL) позволяют маршрутизировать запросы на разные backend'ы на основе условий: path, headers, method и других параметров.
ACL (Access Control List) — механизм условной маршрутизации в HAProxy.
Базовый синтаксис:
acl <name> <criterion> <pattern>Использование:
use_backend <backend> if <acl_name>frontend http_front
bind *:80
# ACL по path
acl is_api path_beg /api
acl is_static path_beg /static
acl is_health path /health
# Маршрутизация
use_backend api_servers if is_api
use_backend static_servers if is_static
use_backend health_servers if is_health
default_backend web_serversPath matchers:
path_beg /api — path начинается с /apipath_end .jpg — path заканчивается на .jpgpath /health — точное совпадение pathpath_sub admin — path содержит adminfrontend http_front
bind *:80
# ACL по методу
acl is_post method POST
acl is_put method PUT
acl is_delete method DELETE
acl is_read_only method GET HEAD
use_backend write_servers if is_post is_put is_delete
use_backend read_servers if is_read_only
default_backend web_serversМетоды:
GET, POST, PUT, DELETE, PATCH, HEAD, OPTIONSfrontend http_front
bind *:80
# ACL по заголовкам
acl is_json hdr(Content-Type) -m json
acl has_auth hdr(Authorization) -m found
acl is_mobile hdr_sub(User-Agent) -i mobile android iphone
use_backend json_servers if is_json
use_backend mobile_servers if is_mobile
default_backend web_serversHeader matchers:
hdr(Name) value — точное совпадениеhdr_sub(Name) value — подстрока в заголовкеhdr_beg(Name) value — начинается сhdr_end(Name) value — заканчивается на-m found — заголовок присутствует-m regex — регулярное выражение-i — case insensitivefrontend http_front
bind *:80
# ACL по статус коду ответа (для http-response)
acl is_error status 500 502 503 504
acl is_not_found status 404
acl is_redirect status 301 302 307
default_backend web_serversacl is_api path_beg /api
acl is_post method POST
# Оба условия должны быть истинны
use_backend api_write_servers if is_api is_postacl is_mobile hdr_sub(User-Agent) -i mobile
acl is_tablet hdr_sub(User-Agent) -i tablet
# Любое условие истинно
use_backend mobile_servers if is_mobile or is_tabletacl is_internal src 10.0.0.0/8
# Отрицание
http-request deny if !is_internalacl is_api path_beg /api
acl is_post method POST
acl is_admin hdr(X-Role) admin
# Сложное условие
use_backend admin_api_servers if is_api is_post is_adminfrontend http_front
bind *:80
# ACL по IP
acl is_internal src 10.0.0.0/8
acl is_office src 192.168.1.0/24
acl is_whitelist src -f /etc/haproxy/whitelist.txt
# Доступ только для внутренних
http-request deny if !is_internal
default_backend web_serversФормат whitelist.txt:
192.168.1.100
192.168.1.101
10.0.0.0/8
frontend multi_port
bind *:80
bind *:443
# ACL по порту
acl is_http dst_port 80
acl is_https dst_port 443
# Redirect HTTP → HTTPS
http-request redirect scheme https if is_http
default_backend web_serversacl is_exact path /healthacl contains_admin path_sub adminacl is_api path_beg /apiacl is_image path_end .jpg .jpeg .png .gifacl is_uuid path -m regex ^/[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$# ACL по числовому значению
acl is_high_load sc_http_req_rate(0) gt 100
acl is_low_traffic sc_http_req_rate(0) lt 10
# Операторы: eq, ne, gt, ge, lt, le# Загрузка из файла
acl blocked_ips src -f /etc/haproxy/blocked_ips.txt
acl allowed_paths path -f /etc/haproxy/allowed_paths.txt
acl bad_bots hdr_sub(User-Agent) -i -f /etc/haproxy/bad_bots.txtПреимущества:
# ACL по времени
acl is_business_hours hour 9-18
acl is_weekend day 1 7 # 1 = воскресенье, 7 = суббота
acl is_night hour 22-6
use_backend night_servers if is_nightФорматы:
hour 9-18 — с 9 до 18 часовhour 9-12,14-18 — с перерывомday 1-5 — будниday 6,7 — выходныеfrontend api_front
bind *:80
# Versioning
acl is_v1 path_beg /api/v1
acl is_v2 path_beg /api/v2
# Resources
acl is_users path_sub /users
acl is_orders path_sub /orders
acl is_products path_sub /products
# Methods
acl is_read_only method GET HEAD
acl is_write method POST PUT DELETE
# Маршрутизация
use_backend api_v1_users_read if is_v1 is_users is_read_only
use_backend api_v1_users_write if is_v1 is_users is_write
use_backend api_v2_servers if is_v2
default_backend api_v1_servers
backend api_v1_users_read
balance roundrobin
server api1 192.168.1.10:8080 check
backend api_v1_users_write
balance leastconn
server api1 192.168.1.10:8080 check
backend api_v2_servers
balance roundrobin
server api2 192.168.1.20:8080 check# Показать ACL
echo "show acl" | socat /var/run/haproxy/admin.sock stdio
# Обновить ACL из файла
echo "update acl /etc/haproxy/blocked_ips.txt" | socat /var/run/haproxy/admin.sock stdio# Логирование срабатывания ACL
http-request set-header X-ACL-Match "%[acl(is_api)]%[acl(is_post)]"# Хорошо
acl is_api path_beg /api
acl from_internal src 10.0.0.0/8
# Плохо (непонятно)
acl a1 path_beg /api
acl a2 src 10.0.0.0/8# Группируйте связанные ACL
# === API Routes ===
acl is_api path_beg /api
acl is_v1 path_beg /api/v1
# === Security ===
acl is_blocked src -f /etc/haproxy/blocked_ips.txt
acl has_auth hdr(Authorization) -m found# Быстрые проверки первыми
acl is_blocked src -f /etc/haproxy/blocked_ips.txt # Быстро (IP lookup)
http-request deny if is_blocked
acl is_api path_beg /api # Медленнее (string match)path_beg, hdr, method, src — основные критерииor, ! (NOT)Изучим продвинутые ACL: rate limiting, гео-блокировка, blacklist/whitelist.
Вопросы ещё не добавлены
Вопросы для этой подтемы ещё не добавлены.