Настройка AWS CloudFront CDN
CloudFront — CDN от Amazon с 450+ точками присутствия, плотно интегрированный с AWS (S3, EC2, ALB, API Gateway). Используется когда инфраструктура уже на AWS или нужен тонкий контроль над кешированием и маршрутизацией.
Создание Distribution через Terraform
# main.tf
resource "aws_cloudfront_distribution" "main" {
enabled = true
is_ipv6_enabled = true
default_root_object = "index.html"
price_class = "PriceClass_200" # Europe + North America + Asia
# Основной origin — Laravel на EC2/ALB
origin {
domain_name = aws_lb.main.dns_name
origin_id = "alb-origin"
custom_origin_config {
http_port = 80
https_port = 443
origin_protocol_policy = "https-only"
origin_ssl_protocols = ["TLSv1.2"]
}
custom_header {
name = "X-Origin-Verify"
value = var.origin_verify_token
}
}
# S3 origin для статических файлов
origin {
domain_name = aws_s3_bucket.assets.bucket_regional_domain_name
origin_id = "s3-assets"
origin_access_control_id = aws_cloudfront_origin_access_control.main.id
}
# Статические ассеты с S3
ordered_cache_behavior {
path_pattern = "/assets/*"
target_origin_id = "s3-assets"
viewer_protocol_policy = "redirect-to-https"
allowed_methods = ["GET", "HEAD"]
cached_methods = ["GET", "HEAD"]
compress = true
cache_policy_id = aws_cloudfront_cache_policy.assets.id
}
# API — без кеша
ordered_cache_behavior {
path_pattern = "/api/*"
target_origin_id = "alb-origin"
viewer_protocol_policy = "https-only"
allowed_methods = ["DELETE", "GET", "HEAD", "OPTIONS", "PATCH", "POST", "PUT"]
cached_methods = ["GET", "HEAD"]
cache_policy_id = data.aws_cloudfront_cache_policy.caching_disabled.id
origin_request_policy_id = data.aws_cloudfront_origin_request_policy.all_viewer.id
}
# Основные страницы — короткий кеш
default_cache_behavior {
target_origin_id = "alb-origin"
viewer_protocol_policy = "redirect-to-https"
allowed_methods = ["DELETE", "GET", "HEAD", "OPTIONS", "PATCH", "POST", "PUT"]
cached_methods = ["GET", "HEAD"]
compress = true
cache_policy_id = aws_cloudfront_cache_policy.pages.id
}
restrictions {
geo_restriction { restriction_type = "none" }
}
viewer_certificate {
acm_certificate_arn = aws_acm_certificate.main.arn
ssl_support_method = "sni-only"
minimum_protocol_version = "TLSv1.2_2021"
}
}
# Cache Policy для статических ассетов
resource "aws_cloudfront_cache_policy" "assets" {
name = "assets-immutable"
min_ttl = 31536000
max_ttl = 31536000
default_ttl = 31536000
parameters_in_cache_key_and_forwarded_to_origin {
cookies_config { cookie_behavior = "none" }
headers_config { header_behavior = "none" }
query_strings_config { query_string_behavior = "none" }
enable_accept_encoding_brotli = true
enable_accept_encoding_gzip = true
}
}
CloudFront Functions — логика на edge
// function.js — запускается на каждом запросе (< 1мс)
// Добавление security headers
function handler(event) {
var response = event.response;
var headers = response.headers;
headers['strict-transport-security'] = {
value: 'max-age=63072000; includeSubDomains; preload'
};
headers['x-content-type-options'] = { value: 'nosniff' };
headers['x-frame-options'] = { value: 'SAMEORIGIN' };
headers['referrer-policy'] = { value: 'strict-origin-when-cross-origin' };
return response;
}
resource "aws_cloudfront_function" "security_headers" {
name = "security-headers"
runtime = "cloudfront-js-2.0"
code = file("function.js")
publish = true
}
Инвалидация кеша при деплое
# AWS CLI: инвалидировать всё
aws cloudfront create-invalidation \
--distribution-id $DISTRIBUTION_ID \
--paths "/*"
# Только HTML-страницы (после публикации контента)
aws cloudfront create-invalidation \
--distribution-id $DISTRIBUTION_ID \
--paths "/blog/*" "/products/*" "/"
// Laravel: инвалидация при публикации статьи
use Aws\CloudFront\CloudFrontClient;
class ArticlePublished
{
public function handle(Article $article): void
{
$client = new CloudFrontClient([
'version' => 'latest',
'region' => 'us-east-1',
]);
$client->createInvalidation([
'DistributionId' => config('services.cloudfront.distribution_id'),
'InvalidationBatch' => [
'Paths' => ['Quantity' => 1, 'Items' => ["/blog/{$article->slug}"]],
'CallerReference' => (string) now()->timestamp,
],
]);
}
}
Origin Shield
Дополнительный промежуточный кеш между edge-узлами и origin-сервером. Уменьшает нагрузку на origin в 10–50 раз для популярного контента:
origin {
origin_shield {
enabled = true
origin_shield_region = "eu-central-1"
}
}
Срок настройки: 1–2 дня с Terraform, включая SSL-сертификат через ACM.







