HTTP compression, cache директивы, buffer tuning
HTTP компрессия уменьшает размер трафика, кэширование снижает нагрузку на backend.
backend web_servers
compression algo gzip
compression type text/html text/plain text/css application/json application/javascript
server web1 192.168.1.10:8080 checkПараметры:
compression algo gzip — алгоритм сжатия (gzip, deflate)compression type — MIME типы для сжатияКлиент: Accept-Encoding: gzip, deflate
↓
HAProxy (сжимает ответ от backend)
↓
Клиент получает: Content-Encoding: gzip (размер уменьшен в 5-10 раз)
backend web_servers
# Gzip (универсальный)
compression algo gzip
# Deflate (меньше overhead)
# compression algo deflate
# Brotli (требует HAProxy с поддержкой)
# compression algo br
compression type text/html text/plain text/css application/json application/javascript image/svg+xml
server web1 192.168.1.10:8080 checkСравнение:
| Алгоритм | Скорость | Степень сжатия | Поддержка |
|---|---|---|---|
| gzip | Быстро | Хорошая | Все браузеры |
| deflate | Быстрее | Средняя | Все браузеры |
| brotli | Медленнее | Отличная | Современные браузеры |
backend web_servers
compression algo gzip
compression type text/html text/css application/json
# Не сжимать если ответ меньше 1KB
compression offload if { res.hdr(Content-Length) gt 1024 }
# Не сжимать для старых браузеров
compression offload if !{ hdr_sub(Accept-Encoding) -i gzip }
server web1 192.168.1.10:8080 checkbackend web_servers
# Backend сам сжимает, HAProxy пропускает
compression offload
compression type text/html text/css application/json
server web1 192.168.1.10:8080 checkКогда использовать:
Content-Encodingglobal
# Выделить память для кэша
cache my_cache {
total-max-size 1024 # 1 GB в MB
max-object-size 10485760 # 10 MB макс размер объекта
max-age 3600 # 1 час макс время жизни
process-vary # Учитывать Vary header
}
backend web_servers
# Включить кэш
http-cache my_cache
# Что кэшировать
http-cache-rule cache-static path_end .css .js .png .jpg .gif .svg .ico 86400
http-cache-rule cache-api path_beg /api/public 300
server web1 192.168.1.10:8080 checkПараметры cache:
total-max-size — общий размер кэша в MBmax-object-size — макс размер одного объекта в bytesmax-age — макс время жизни в секундахprocess-vary — учитывать Vary headerbackend web_servers
http-cache my_cache
# Статика — 24 часа
http-cache-rule cache-static path_end .css .js .png .jpg .gif .svg .ico 86400
# Публичный API — 5 минут
http-cache-rule cache-api path_beg /api/public 300
# HTML страницы — 1 минута
http-cache-rule cache-html content-type text/html 60
# Не кэшировать личные данные
http-cache-rule no-cache path_beg /api/user 0
http-cache-rule no-cache hdr_set(Cookie) 0
server web1 192.168.1.10:8080 checkbackend web_servers
http-cache my_cache
# Кэш по URL + Accept-Encoding
http-cache-key url
http-cache-key hdr(Accept-Encoding)
# Кэш по URL + Cookie (для персонализированного контента)
# http-cache-key url
# http-cache-key req.cooki(SESSIONID)
server web1 192.168.1.10:8080 checkbackend web_servers
http-cache my_cache
# Учитывать Cache-Control от backend
http-cache-ignore-no-cache
# Переопределить TTL для определённых типов
http-cache-rule override-ttl content-type text/html 300
server web1 192.168.1.10:8080 checkglobal
# Размер буфера для HTTP заголовков
tune.bufsize 16384
# Буфер для rewrite операций
tune.maxrewrite 1024
# Размер буфера для компрессии
tune.comp.maxlevel 9Параметры:
tune.bufsize — размер буфера (по умолчанию 4096)tune.maxrewrite — место для rewrite операцийtune.comp.maxlevel — уровень компрессии (1-9)global
# Большие JWT токены
tune.bufsize 32768
# Много кастомных заголовков
tune.bufsize 16384Признаки проблем:
400 Bad Request с большими заголовками502 Bad Gatewayglobal
# Кэш 1GB
cache web_cache {
total-max-size 1024
max-object-size 10485760
max-age 3600
process-vary
}
defaults
mode http
option httplog
timeout connect 5s
timeout client 30s
timeout server 30s
frontend http_front
bind *:80
# Сжатие запросов от клиента (если backend поддерживает)
# http-request set-header Accept-Encoding "gzip, deflate"
use_backend web_servers
backend web_servers
# Компрессия ответов
compression algo gzip
compression type text/html text/plain text/css application/json application/javascript image/svg+xml
# Кэширование
http-cache web_cache
# Правила кэширования
http-cache-rule cache-static path_end .css .js .png .jpg .gif .svg .ico 86400
http-cache-rule cache-api path_beg /api/public 300
http-cache-rule cache-html content-type text/html 60
# Не кэшировать
http-cache-rule no-cache path_beg /api/user 0
http-cache-rule no-cache path_beg /admin 0
http-cache-rule no-cache hdr_set(Cookie) 0
# Buffer tuning
tune.bufsize 16384
server web1 192.168.1.10:8080 check
server web2 192.168.1.11:8080 checklisten stats
bind *:8404
stats enable
stats uri /
stats refresh 5s
# Показать метрики кэша
stats show-legendsМетрики:
# Экспорт метрик кэша
prometheus-exporter
prometheus-exporter rules
cache_hits_total
cache_misses_total
cache_objects
cache_bytes# Запрос с Accept-Encoding
curl -H "Accept-Encoding: gzip" -v http://example.com/
# Проверка Content-Encoding в ответе
curl -H "Accept-Encoding: gzip" -I http://example.com/
# Content-Encoding: gzip# Первый запрос (miss)
curl -v http://example.com/static/style.css
# Второй запрос (hit)
curl -v http://example.com/static/style.css
# Проверка заголовков кэша
curl -I http://example.com/static/style.css
# X-Cache: HIT# Логирование hit/miss
log-format "%ci:%cp %ft %b/%s %ST %B %{+Q}r cache=%[res.hdr(X-Cache)]"# ✅ Хорошо
http-cache-rule cache-static path_end .css .js .png .jpg 86400
http-cache-rule cache-api path_beg /api/public 300
# ❌ Плохо (личные данные)
# http-cache-rule cache-user path_beg /api/user 300# ✅ Сжимать текстовые типы
compression type text/html text/css application/json
# ❌ Не сжимать бинарные (уже сжаты)
# compression type image/png image/jpeg video/mp4# ✅ Для большинства случаев
tune.bufsize 16384
cache my_cache { total-max-size 1024 }
# ❌ Слишком большой (память)
# tune.bufsize 1048576
# cache my_cache { total-max-size 10240 }Изучим SSL/TLS: сертификаты, SNI, OCSP stapling, TLS 1.3.
Вопросы ещё не добавлены
Вопросы для этой подтемы ещё не добавлены.