IaC Bazaar

Edge Redirector Architecture, Use Cases and IaC Automation

IaC Bazaar·
Professional header image for educational tutorial: Edge Redirector Architecture, Use Cases and IaC Automation

Traffic redirection at the edge sounds simple until you are managing dozens of domains, handling multi-region failover, and trying to keep your infrastructure reproducible. That is where an edge redirector becomes an essential component in your architecture toolkit.

In this tutorial, we will break down what an edge redirector is, how it fits into modern distributed systems, and when you should reach for it over alternative approaches like application-level redirects or load balancer rules. More importantly, we will walk through real-world use cases including domain consolidation, A/B routing, and geo-based traffic steering.

Beyond the architecture concepts, this guide goes a step further by covering Infrastructure as Code automation. You will learn how to provision and manage edge redirector configurations programmatically using tools like Terraform, keeping your redirect logic version-controlled, auditable, and repeatable across environments.

Whether you are designing a new system or refactoring an existing one, this post gives you the mental models and practical patterns to implement edge redirection with confidence. Intermediate familiarity with DNS, CDN concepts, and basic IaC workflows will help you get the most out of what follows.

What Is an Edge Redirector?

"Edge redirector" is one of those terms that means something precise to every practitioner who uses it, yet those precise meanings point to structurally different architectures. A CDN engineer, a red team operator, and a Kubernetes platform engineer all reach for the same label, but they are describing distinct systems unified by a single architectural principle: the decision about where traffic goes is made at the network perimeter, before the request ever reaches the origin.

That principle is exactly why "edge" is the operative word. Whether you are talking about a CloudFront distribution intercepting a request at a point-of-presence, an NGINX instance filtering C2 beacon traffic, or a Kubernetes Ingress controller evaluating an HTTPRoute rule, the decision point sits outside the origin infrastructure. This placement has three compounding effects on your system. First, latency: routing decisions made at geographically distributed edge nodes avoid the round-trip cost of consulting a centralized origin. Second, security posture: malicious or misconfigured requests can be blocked, rewritten, or redirected before they touch internal services. Third, observability: the edge layer functions simultaneously as a control point and a logging chokepoint, which is precisely why red team operators invest significant effort in evading it, as detailed in this red team C2 redirector design guide.

It also helps to separate a redirector from the adjacent concepts of reverse proxy and load balancer, since these three are frequently conflated. A redirector issues HTTP 3xx responses (301, 302, 307, or 308) or transparently forwards traffic with modified headers, without necessarily terminating the TLS session. A reverse proxy terminates the client connection, opens a separate upstream connection, and reassembles the response; it is bidirectionally connection-aware. A load balancer distributes traffic across a backend pool based on health and capacity, operating at L4 or L7, without the semantic goal of URL transformation. In practice, edge redirectors in the red team domain blur this boundary: an NGINX-based redirector selectively proxies beacon traffic while returning benign content to scanners, making it functionally closer to a selective reverse proxy. The label "redirector" in that context describes operational intent, not the HTTP response code issued.

Across four domains, the term carries distinct architectural weight. In CDN traffic steering, handling redirects at the CloudFront edge means embedding redirect logic at distributed PoPs so that HTTP-to-HTTPS enforcement or geo-based routing never incurs an origin round-trip. In red team C2 obfuscation, a redirector is an attacker-controlled intermediate hop that conceals the real C2 server IP from defenders and threat intelligence feeds. In web application edge routing, platforms like Lambda@Edge and Cloudflare Workers execute redirect and rewrite logic as code at the edge, enabling canary deployments, A/B splits, and authentication header injection globally. In Kubernetes Ingress and Gateway API, redirect rules are expressed as annotations or HTTPRoute RequestRedirect filters, with a controller such as NGINX, Traefik, or Envoy translating those declarations into running proxy configuration.

The rest of this guide cuts through that ambiguity by examining infrastructure-as-code automation patterns for each domain, with security hardening and supply chain integrity considerations threaded throughout.

Edge Redirector Architectures

Edge Redirector Architectures

Before selecting an IaC module or writing a single Terraform resource, you need to identify which architectural pattern governs your edge redirector. Each variant carries distinct assumptions about traffic volume, operational security posture, persistence requirements, and the underlying cloud primitives involved. Conflating them leads to misconfigured infrastructure, exposed endpoints, and wasted engineering effort.

CDN-Based Edge Redirectors

CDN-layer redirectors operate entirely at points of presence distributed across a provider's global network, processing redirect logic before requests ever reach an origin server. This pattern is purpose-built for traffic shaping, URL management, and latency reduction at scale. Managed products in this category intercept HTTP/HTTPS requests at the edge, evaluate redirect rules against request attributes such as URL path, geolocation, or query parameters, and return the appropriate response without burdening origin infrastructure. The primary operational benefit is offloading redirect processing from application servers, which eliminates a class of origin-side configuration errors and removes latency that would otherwise accumulate across a round-trip to the backend. From an IaC perspective, CDN redirectors are expressed through provider-specific resources: CloudFront behaviors with Lambda@Edge functions, WAF-integrated response headers, or Front Door routing rules defined in Terraform configuration blocks. Security teams should treat these configurations as sensitive artifacts because a misconfigured redirect rule can expose internal endpoints or create open redirect vulnerabilities that bypass perimeter controls.

Red Team and C2 Redirector Architectures

In offensive security operations, an edge redirector serves a fundamentally different function: it acts as an intermediate hop that prevents direct communication between implants and the team server, obscuring the C2 backend from network defenders and EDR telemetry. The canonical pattern is a two-hop chain where the first hop receives raw implant callbacks and forwards them using Proxy Protocol or plain TCP tunneling, while the second hop terminates TLS and applies filtering rules before passing authenticated traffic to the actual C2 server. Traditional implementations rely on persistent VPS instances running nginx or Apache with mod_rewrite rules, but this approach leaves a permanent IP footprint that defenders can fingerprint and block. More sophisticated operators layer CDN fronting on top of this architecture, routing implant traffic through provider-owned hostnames so that blocking the apparent destination would disrupt legitimate enterprise services. A practical reference for this pattern is building C2 redirectors with nginx and Apache, which illustrates how persistent redirector nodes compare structurally to serverless alternatives. The most common operational failure mode remains direct implant callbacks that bypass the redirector entirely, exposing the team server IP in telemetry data.

Serverless Edge Redirectors

Serverless redirectors replace the persistent VPS with ephemeral compute that exists only for the milliseconds required to process and forward a single request. AWS Lambda behind API Gateway is the most widely adopted implementation: the public-facing endpoint uses an *.execute-api.amazonaws.com hostname carrying a valid Amazon-issued TLS certificate, making blanket domain blocking operationally untenable for defenders. The redirector logic itself is typically a lightweight transparent HTTP proxy of roughly forty lines of Python, receiving the inbound request via API Gateway and forwarding it to the backend origin. The cost advantage over persistent infrastructure is significant; intermittent C2 check-ins through Lambda's per-request pricing model cost pennies per month compared to five to twenty dollars monthly for a continuously running VPS. Cloudflare Workers offer a comparable serverless pattern using V8 isolates distributed across edge nodes globally, with cold-start characteristics and geographic distribution that differ meaningfully from Lambda. Teardown and redeployment are single-command operations, making this pattern highly suitable for per-engagement infrastructure. The Hacker Hermanos walkthrough on serverless C2 redirectors documents the full Lambda deployment lifecycle including Terraform-managed provisioning and teardown cycles. Automated provisioning using Ansible playbooks with Jinja2 templates allows per-operation parameterization, as demonstrated in the anubissec Lambda infrastructure automation project.

Kubernetes and Containerized Edge Patterns

Kubernetes-native edge redirectors express redirect logic through ingress controllers, with NGINX Ingress and Envoy-based implementations being the most operationally common. Redirect rules are declared as annotations on Ingress resources or as Envoy filter configurations in a service mesh, enabling redirect behavior to be versioned alongside application manifests and managed through GitOps workflows. This pattern is particularly relevant for platform engineering teams that need consistent redirect policies across multiple microservices without maintaining separate redirect infrastructure. Containerized redirector fleets extend this concept into offensive security contexts by isolating each redirector node in its own container, enabling rapid spin-up and teardown and enforcing configuration consistency across the entire fleet. Terraform automates the provisioning of the underlying node groups or managed node pools, while Helm charts or raw Kubernetes manifests handle the redirect logic layer. The separation of infrastructure provisioning from configuration deployment is a key architectural principle that carries through all of these patterns and becomes the foundation for reusable IaC modules.

CDN and CloudFront Redirect Behaviors

CloudFront implements redirect logic through two distinct edge-compute services: CloudFront Functions and Lambda@Edge. CloudFront Functions trigger at the viewer-request and viewer-response stages, executing across 225+ global edge locations in under one millisecond, making them ideal for lightweight redirect operations. Lambda@Edge extends this with origin-request and origin-response hooks, running at 13 regional edge cache locations with longer execution windows suited for complex logic. When redirect rules must fire after a cache miss but before the request reaches your origin, the Lambda@Edge origin-request hook is the correct instrument.

The most common patterns built on these hooks include HTTP-to-HTTPS forced redirects via viewer-request inspection, www-to-apex domain normalization through URL rewriting, and legacy URL migration using 301 permanent redirects to preserve SEO equity. Geo-based traffic steering uses CloudFront's injected geographic headers at the origin-request stage to route requests to region-appropriate endpoints. CloudFront KeyValueStore further enables sub-millisecond lookups against large redirect mapping tables without round-tripping to the origin.

AWS WAF, when attached to a CloudFront distribution, adds a complementary security layer by evaluating IP reputation lists, geographic restriction rules, and rate-based conditions before redirect logic even executes. This allows operators to block or challenge suspicious traffic upstream of any routing decision.

Other CDN providers offer functionally equivalent mechanisms with provider-specific Terraform resources. Cloudflare redirect behavior is managed through the cloudflare_ruleset resource using Page Rules or Transform Rules. Azure Front Door exposes redirect actions via azurerm_cdn_frontdoor_rule. Fastly supports edge redirect logic through VCL or Compute@Edge. Each provider's Terraform provider surfaces these capabilities as declarative resources, enabling consistent IaC-driven redirect automation regardless of the underlying CDN platform.

Two-Hop Red Team Redirector with nginx and Proxy Protocol

The two-hop nginx redirector is the most operationally resilient pattern available for C2 traffic routing, and its architecture maps cleanly onto IaC primitives.

Hop1 is intentionally minimal. It runs nginx's stream {} module, not the http {} module, which means it operates at the TCP layer and never inspects or terminates TLS. Its only job is to prepend a Proxy Protocol header carrying the original client IP, then forward the raw byte stream to hop2. This design means hop1 has near-zero attack surface: no TLS certificates to rotate, no application logic to misconfigure, and no knowledge of the C2 server address. Because it processes traffic at the stream layer, even encrypted implant traffic passes through opaque and intact.

Hop2 is where enforcement happens. It terminates TLS, reads the Proxy Protocol header via the real_ip_header proxy_protocol and set_real_ip_from directives, and then applies conditional proxy_pass or redirect logic based on User-Agent strings and URI patterns. Requests that match expected implant signatures are forwarded to the C2 server on a private, non-routable address. Requests that do not match, such as those from automated scanners or blue team enumeration tools, receive a redirect to a benign decoy site. The C2 server itself never holds a public IP, which removes it entirely from passive internet scanning datasets.

The OPSEC value of this compartmentalisation is concrete. If hop1 is blocked, seized, or identified by a defender, the C2 server address is not exposed. Hop2 can be redeployed in minutes using the same IaC configuration, since its state is entirely code-defined. This burn-and-redeploy model is what makes engagements survivable when a single hop is burned. According to practitioner accounts, unprotected C2 infrastructure without this separation can be neutralised within 36 hours of operator activity beginning.

Static IP decoupling is the mechanism that preserves operational continuity across redeployments. On GCP, this means allocating a google_compute_address resource independently and binding it to the instance via nat_ip. On AWS, the equivalent is an Elastic IP resource attached to an EC2 instance. On Azure, it is a azurerm_public_ip resource with allocation_method = "Static". When an instance is destroyed and recreated, the static IP persists in the cloud account, allowing domain bindings, TLS certificates issued to that IP or its associated domain, and any allow-list entries at hop2 to survive the redeployment cycle without manual intervention.

The full stack, including compute instances, static IPs, firewall rules, and network interfaces, should be expressible in a single Terraform root module. A terraform apply provisions the environment; a terraform destroy removes every resource cleanly. This is not a convenience feature: it is an operational requirement. Manual deployments introduce configuration drift, undocumented firewall exceptions, and residual resources that outlive the engagement. Building red team infrastructure with Terraform represents the community-validated baseline for this pattern, pairing Terraform for resource provisioning with Ansible for post-provision nginx configuration, applied via a null_resource local-exec provisioner. For teams that need verified, security-scanned, and cosign-signed modules for this stack rather than assembling it from scratch, IaC Bazaar's catalog offers a direct path to production-ready redirector infrastructure without the module authoring overhead.

Kubernetes Ingress and Gateway API HTTPRoute Redirect Rules

Kubernetes Ingress controllers handle cluster-edge redirect logic through controller-specific annotations. With nginx-ingress, you declare permanent redirects via nginx.ingress.kubernetes.io/permanent-redirect and enforce HTTPS upgrades via nginx.ingress.kubernetes.io/ssl-redirect: "true". Traefik and Contour follow analogous but incompatible annotation schemas, meaning redirect manifests are not portable across controllers. This fragmentation is a practical maintenance liability in multi-cluster environments where controllers differ between EKS and GKE deployments.

The Gateway API HTTPRoute resource resolves this through structured RequestRedirect filters. A single filter block specifies scheme, hostname, path, and statusCode fields within one manifest, replacing scattered annotations with a typed, validated spec. The API separates infrastructure concerns (GatewayClass, Gateway) from application routing (HTTPRoute), letting platform engineers and developers operate in distinct RBAC boundaries. As the 2026 Gateway API landscape guide notes, this represents the most significant shift in Kubernetes networking since Ingress was introduced in 2015.

Istio extends HTTPRoute redirect filters beyond the ingress boundary into east-west traffic via the GAMMA initiative. Redirect logic executes at the sidecar or ambient waypoint level, enabling service-to-service redirect enforcement without requiring traffic to exit and re-enter the cluster edge.

Managing these manifests through Terraform using the kubernetes_manifest resource ties redirect lifecycle directly to cluster provisioning. When your EKS or GKE cluster is defined in the same Terraform plan as its HTTPRoute rules, redirect policy changes go through the same plan and apply workflow as node group scaling or VPC configuration. IaC Bazaar's verified Kubernetes modules extend this pattern with cosign-signed, security-scanned manifests, eliminating the supply chain risk of hand-authored routing configurations in production clusters.

Serverless Edge Redirects with Lambda@Edge and Cloudflare Workers

Lambda@Edge attaches Node.js functions to CloudFront distributions, intercepting viewer-request and origin-request lifecycle events to inspect path, query string, cookie, or geographic headers and return HTTP 301/302 responses before traffic ever reaches the origin. The key nuance is that Lambda@Edge executes in the nearest AWS region, not directly on the CloudFront edge PoP, introducing a potential cold-start penalty. Benchmarks from 2026 show Lambda@Edge cold starts reaching approximately 800ms versus roughly 1ms for Cloudflare Workers, which uses V8 isolates to eliminate container spin-up overhead entirely.

Cloudflare Workers run JavaScript and TypeScript across 300+ global cities, enabling arbitrarily complex conditional redirect trees: locale-based routing, cookie-gated feature flags, A/B redirect splits, and path normalization logic that far exceeds static rule sets. Vercel Edge Middleware follows the same V8 isolate model, extending this programmable redirect pattern natively into Next.js deployments. For redirect-heavy workloads, serverless performance comparisons consistently favor isolate-based runtimes for latency-sensitive operations.

The critical operational tradeoff versus Terraform-managed nginx instances is auditability. Nginx redirect configurations live in version-controlled HCL modules, are statically analyzable, and can be security-scanned as first-class IaC artifacts. Serverless edge functions, by contrast, are deployed via Wrangler CLI or Lambda console workflows that sit outside standard Terraform state. This makes cosign-signed, pre-validated redirect modules, like those available through IaC Bazaar, a meaningful governance advantage for compliance-conscious platform teams choosing nginx-based edge redirectors over serverless alternatives.

Why Automate Edge Redirectors with IaC?

Every redirector configuration shown in the preceding sections, whether a CloudFront behavior, a two-hop nginx proxy chain, or a Kubernetes HTTPRoute rule, carries a shared operational risk: the moment a human edits it outside of version control, that infrastructure begins to diverge from its intended state. What is Infrastructure as Code (IaC)? is fundamentally an answer to this problem. A redirect rule added through the AWS Console or patched directly into a live nginx.conf is invisible to Git history, cannot be reviewed in a pull request, and has no rollback path. Configuration drift accumulates silently across environments until a production incident or a compliance audit forces reconciliation. For redirect infrastructure specifically, drift is not merely an operational nuisance; a diverged proxy_pass target or an unreviewed Location: header rewrite can reroute user traffic to an unintended or attacker-controlled destination without triggering any runtime alert.

Static Validation Catches Redirect Misconfigurations Before Production

Open redirect vulnerabilities are a persistent misconfiguration class in redirect infrastructure, and they are disproportionately introduced through manual, unreviewed edits. A permissive proxy_pass $host; directive in nginx, for example, allows an attacker to supply an arbitrary Host header and proxy requests to any origin, effectively turning your edge node into an open relay. When redirect rules live in Terraform HCL or an Ansible playbook, a static analysis pass using tools such as Checkov, tfsec, or OPA Conftest can evaluate the configuration against policy rules before a single packet reaches production. The shift-left enforcement model means that a wildcard proxy_pass pattern is rejected at CI pipeline evaluation time, not discovered during a penetration test or a bug bounty submission. This validation layer is structurally unavailable to teams managing redirect rules through console clicks or live-file edits.

Ephemeral Infrastructure Requires Repeatable, Auditable Workflows

Red team operators running adversarial simulations and blue team defenders standing up traffic-analysis environments share a common infrastructure requirement: the redirector must be fully operational within an hour and completely removed within another hour, with no residual state. This lifecycle is only reliably achievable with IaC. A terraform apply against a verified module provisions the compute instance, assigns the static IP, installs and configures nginx with the correct proxy rules, and attaches the firewall policy as a single atomic operation. A subsequent terraform destroy removes every resource, and the entire lifecycle is recorded in version control with timestamps and operator attribution. No manual teardown checklist can match that auditability guarantee.

Supply Chain Integrity for Redirect Modules

A community Ansible role or Terraform module for nginx or CloudFront pulled from an unverified registry is a meaningful supply chain risk. A malicious contributor could embed a proxy_pass target pointing to an attacker-controlled host, silently routing a percentage of production traffic through an exfiltration endpoint. Configuration drift and supply chain exposure are now recognized risk categories even in government IT environments, reflecting broad institutional acknowledgment of the problem. IaC Bazaar addresses this vector directly: every Terraform, OpenTofu, and Ansible module in the catalog is statically validated, security-scanned for known misconfiguration patterns, and cosign-signed, meaning the artifact's provenance is cryptographically verifiable before it executes in your pipeline. For redirect infrastructure, where a single compromised proxy_pass rule can silently exfiltrate traffic, that supply chain guarantee is a security control, not a convenience feature.

Compliance Traceability Extends to Routing Rules

SOC 2 CC6, PCI-DSS Requirement 6, and FedRAMP's CM and CA control families all require demonstrable change control over systems that handle user or cardholder traffic. Redirect and routing rules determine where that traffic flows, placing them squarely within audit scope. A GitOps workflow anchors every redirect rule change to a pull request, a reviewer approval, and a merge timestamp; the automated apply log provides the deployment evidence. Auditors in regulated environments increasingly expect not just that IaC exists, but that drift between declared and actual infrastructure state is continuously detected and remediated. Organizations that manage redirect rules outside IaC cannot produce this evidence chain and face a material compliance gap as audit standards continue to tighten.

Provisioning an Edge Redirector with Terraform

The three architecture types covered in previous sections each map to a distinct Terraform provisioning pattern. Working through all three in sequence gives you a complete picture of how redirect logic translates from conceptual design into deployable HCL.

Pattern 1: CloudFront Behaviors

The CDN-layer redirector is expressed entirely through aws_cloudfront_distribution and its companion aws_cloudfront_function resource. A CloudFront Function attached to the viewer-request event intercepts every inbound request before it reaches your origin, executes your redirect logic in sub-millisecond JavaScript, and returns a 301 or 302 directly to the client. The Terraform representation keeps the two concerns cleanly separated: the distribution resource owns routing and caching policy, while the function resource owns redirect logic as a versioned code artifact.

resource "aws_cloudfront_function" "redirector" {
 name = "edge-redirector"
 runtime = "cloudfront-js-2.0"
 publish = true
 code = file("${path.module}/redirect.js")
}

resource "aws_cloudfront_distribution" "edge_redirector" {
 enabled = true
 http_version = "http2and3"
 price_class = "PriceClass_100"

 origin {
 domain_name = var.origin_domain
 origin_id = "primary-origin"

 custom_origin_config {
 http_port = 80
 https_port = 443
 origin_protocol_policy = "https-only"
 origin_ssl_protocols = ["TLSv1.2"]
 }
 }

 default_cache_behavior {
 target_origin_id = "primary-origin"
 viewer_protocol_policy = "redirect-to-https"
 allowed_methods = ["GET", "HEAD"]
 cached_methods = ["GET", "HEAD"]

 function_association {
 event_type = "viewer-request"
 function_arn = aws_cloudfront_function.redirector.arn
 }
 }

 restrictions {
 geo_restriction { restriction_type = "none" }
 }

 viewer_certificate {
 cloudfront_default_certificate = true
 }
}

The redirect.js file referenced by file() contains your URL rewrite rules and lives alongside the module, making the entire redirector auditable as a single version-controlled unit.

Pattern 2: Compute-Based Two-Hop Redirector

When you need a static, routable IP for DNS pinning or firewall allowlisting, the compute instance plus elastic IP pattern is the right primitive. On AWS, aws_instance provides the VM and aws_eip pins a stable public address to it regardless of instance replacement cycles.

resource "aws_instance" "hop1" {
 ami = var.ami_id
 instance_type = "t3.micro"
 subnet_id = var.public_subnet_id
 user_data = templatefile("${path.module}/nginx-hop1.tftpl", {
 hop2_ip = aws_eip.hop2.public_ip
 })
 tags = { Name = "edge-redirector-hop1" }
}

resource "aws_eip" "hop1" {
 instance = aws_instance.hop1.id
 domain = "vpc"
}

The same logical pattern is portable across cloud providers with minimal variable substitution. On GCP, replace aws_instance with google_compute_instance and aws_eip with google_compute_address, setting address_type = "EXTERNAL". On Azure, substitute azurerm_linux_virtual_machine paired with azurerm_public_ip using allocation_method = "Static". In each case, the module accepts an ami_id or image_id variable and an instance_type variable; the networking primitives differ only in resource type names and provider-specific argument keys. Wrapping all three providers behind a single module interface with a var.cloud_provider input is a straightforward refactor that produces a genuinely cloud-agnostic redirector primitive.

Pattern 3: Kubernetes Ingress

For cluster-edge redirects, the kubernetes_ingress_v1 resource directly encodes the annotation-driven rules discussed in the Kubernetes section into Terraform state.

resource "kubernetes_ingress_v1" "redirector" {
 metadata {
 name = "edge-redirector"
 namespace = var.namespace
 annotations = {
 "nginx.ingress.kubernetes.io/permanent-redirect" = "https://new.example.com$request_uri"
 "nginx.ingress.kubernetes.io/use-regex" = "true"
 }
 }
 spec {
 ingress_class_name = "nginx"
 rule {
 host = var.source_host
 http {
 path {
 path = "/"
 path_type = "Prefix"
 backend {
 service {
 name = "placeholder-svc"
 port { number = 80 }
 }
 }
 }
 }
 }
 }
}

State Management for Ephemeral Redirectors

Redirector infrastructure is frequently short-lived; a campaign-scoped redirector or a feature-flag A/B routing layer may exist for days rather than years. Storing that state in the same backend as your persistent origin cluster creates an entanglement risk: a terraform destroy targeting the redirector stack can reference, and in some misconfigured pipelines inadvertently affect, persistent resources sharing the same state file. The correct mitigation is state isolation. Use a dedicated Terraform workspace (terraform workspace new redirector-campaign-01) or a separately prefixed backend key such as s3://tf-state/redirectors/campaign-01/terraform.tfstate, keeping it structurally independent from the EKS cluster or primary distribution state. This boundary makes terraform destroy scoped and safe by design.

Using Verified Modules from IaC Bazaar

Hand-rolling the HCL blocks above is viable for a single deployment, but it accumulates maintenance surface across teams. IaC Bazaar offers verified CloudFront and nginx redirector modules that are statically validated and security-scanned before publication. Before running terraform init, run cosign verify against the module artifact to confirm its signature against IaC Bazaar's published signing key. This cosign verification step is a concrete supply chain integrity gate: it proves the module you are about to initialize is byte-for-byte the artifact that was scanned and signed, with no tampering in transit. For security-sensitive redirector deployments, particularly two-hop C2 proxies or production CDN distributions, this verification step belongs in your CI pipeline as a required check before any terraform plan executes.

CloudFront Redirect Behaviors with aws_cloudfront_distribution

The aws_cloudfront_distribution resource consolidates four distinct redirect mechanisms into a single Terraform configuration file, making it the primary IaC surface for CDN-layer redirect policy on AWS.

HTTPS enforcement operates through the viewer_protocol_policy argument inside ordered_cache_behavior blocks. Setting this to "redirect-to-https" instructs CloudFront edge nodes to issue an HTTP 301 before any request reaches the origin, eliminating the need for redirect logic on your load balancer or application server. Multiple ordered_cache_behavior blocks are evaluated in array order, giving you per-path control: enforce HTTPS on /api/* with aggressive cache TTLs while applying separate settings on /static/*.

Lambda@Edge redirect functions attach via a lambda_function_association block nested inside any cache behavior. Targeting the viewer-request event executes the function before CloudFront consults its cache or contacts the origin. This is the correct attachment point for dynamic redirect tables, locale-based routing, and slug migration logic. The Lambda function must be deployed in us-east-1 regardless of origin region, which requires a provider alias in your Terraform configuration.

Custom error responses via custom_error_response blocks map specific HTTP error codes to a response_page_path and override response_code. The canonical SPA pattern maps both 403 and 404 responses to /index.html with a 200 status, handling S3 OAC behavior where missing keys return 403 rather than 404. The same pattern applies to legacy URL migration by redirecting error responses to a canonical URL at the CDN layer rather than the application layer.

WAF integration via the web_acl_id argument associates a WAFv2 Web ACL scoped to CLOUDFRONT with the distribution. WAF BLOCK actions produce 403 responses at the edge; pairing them with custom_error_response blocks routes rate-limited or geo-blocked requests to an appropriate explanation page. This co-locates redirect behavior, access control rules, and cache policy in a single versioned .tf file, which is a measurable IaC hygiene improvement over managing these concerns across separate systems.

Provisioning a Two-Hop Redirector with Terraform Compute Resources

A two-hop redirector module provisions four core resources in a single terraform apply run: two compute instances (hop1 and hop2) and two static IPs bound to each. Using a count = 2 meta-argument across both google_compute_address and google_compute_instance resource blocks keeps the module concise and ensures both instances are torn down symmetrically on destroy. Terraform output blocks close the wiring loop automatically, exposing hop2's static IP as the forwarding target injected into hop1's nginx configuration by the downstream Ansible layer. This eliminates manual IP transcription between provisioning steps and makes the hop chain fully reproducible from a single variable file.

Firewall rules belong in Terraform resource arguments, not in post-provisioning console edits. For hop1, an inbound rule should accept traffic only from operator-controlled source CIDRs supplied via an operator_source_cidrs input variable. A corresponding outbound rule should permit only TCP 443 (Proxy Protocol) from hop1 to hop2's static IP, with all other egress denied. On GCP, instance tags bind google_compute_firewall rules to the correct instances. AWS equivalents use aws_security_group with explicit ingress and egress blocks referencing aws_eip.hop2.public_ip. Expressing these constraints as code means every deployment enforces identical posture and any deviation surfaces immediately in terraform plan output.

For Ansible integration, two patterns are available. The first uses a null_resource with a local-exec provisioner that triggers ansible-playbook immediately after compute resources are created, passing Terraform outputs as inventory. The triggers argument should reference the instance IDs to prevent redundant playbook runs on unrelated apply executions. The second, cleaner pattern separates concerns entirely: Terraform outputs the provisioned IPs as CI/CD pipeline artifacts, and a downstream stage handles Ansible execution independently.

The module's input variables should cover cloud_provider, instance_size, region, ami_image_id, and operator_source_cidrs. Abstracting the image reference to a variable lets the same root module deploy Ubuntu equivalents on AWS, GCP, or Azure without any code modification, just a different variable file per target environment.

Before using terraform destroy in live red team operations, validate the destroy workflow explicitly in a staging environment. Confirm that both instances are terminated and both static IPs are released in a single invocation. Unreleased IPs or lingering instances create attribution risk that negates the operational security benefit of ephemeral infrastructure. IaC Bazaar's verified, cosign-signed redirector modules enforce this lifecycle discipline by design, giving operators a pre-validated destroy path without debugging state inconsistencies under operational pressure.

Managing Kubernetes Ingress Redirects via Terraform

The kubernetes_ingress_v1 resource in terraform-provider-kubernetes accepts a metadata.annotations block where you declare nginx-ingress redirect directives directly alongside your cluster resources. Annotations like nginx.ingress.kubernetes.io/permanent-redirect and nginx.ingress.kubernetes.io/rewrite-target are expressed as Terraform-managed configuration, meaning redirect rules share the same state file as your EKS or GKE cluster definition. This co-location matters operationally: redirect drift becomes visible in terraform plan output rather than surfacing as a silent configuration gap between your cluster and your routing rules. Teams on Kubernetes 1.22 or later must use the _v1 resource variant, since the deprecated networking.k8s.io/v1beta1 Ingress API was removed in that release.

For clusters adopting the Gateway API, kubernetes_manifest is the correct Terraform resource for managing HTTPRoute objects with RequestRedirect filters. This filter-based approach is implementation-agnostic: the same HTTPRoute manifest produces consistent redirect behavior whether your Gateway controller is Envoy Gateway, Cilium, or another conformant implementation. Note that RequestRedirect and rewrite filters are mutually exclusive within a single rule, so path rewrites and redirects require separate route entries.

Separating your Terraform root modules by concern directly reduces blast radius. Cluster provisioning (aws_eks_cluster, google_container_cluster) changes infrequently and carries high risk on re-plan. Ingress configuration (kubernetes_ingress_v1, kubernetes_manifest) changes with every application deployment cycle. Isolating these into distinct modules means redirect rule updates run their own targeted plan without touching cluster-level state.

Vizier, IaC Bazaar's orchestrator, handles the dependency sequencing between these module layers automatically. It models cluster provisioning and ingress redirect configuration as ordered stack components, ensuring the cluster reaches a ready state before ingress resources are applied, without requiring manual coordination between plan runs.

Configuring Edge Redirectors with Ansible

Ansible enters the workflow the moment terraform apply completes. With compute instances running and static IPs bound, Ansible takes ownership of everything above the OS layer: package installation, nginx or Caddy configuration, TLS certificate provisioning, and Proxy Protocol listener setup. This clean separation between provisioning and configuration is what makes the pattern repeatable across engagements and cloud providers. Terraform hands off a known-good host inventory; Ansible drives every host in that inventory to an identical, verified configuration state.

nginx Redirector Role Structure

A production-grade Ansible nginx redirector role follows a standard directory layout: tasks/main.yml handles installation and site enablement, handlers/main.yml defines the nginx reload handler, templates/redirector.conf.j2 holds the Jinja2-parameterised nginx config, and vars/main.yml carries the upstream hop2 IP and domain-specific values. The task sequence matters: install nginx with state: present, template the config to /etc/nginx/sites-available/redirector.conf, create the symlink into sites-enabled/, run nginx -t as a validation step using the command module with a changed_when: false guard, and then notify the reload handler only if the template task reported a change. Using the validate parameter on the template module (validate: nginx -t -c %s) catches syntax errors before the file is written to disk, preventing a broken config from ever reaching the filesystem. The handler itself calls systemctl reload nginx rather than restart, keeping existing connections alive during config updates.

Proxy Protocol Configuration on hop2

On hop2, the nginx listener must be declared with both SSL and Proxy Protocol enabled simultaneously. The correct directive is listen 443 ssl proxy_protocol;, not two separate listen lines. Without the proxy_protocol parameter, nginx discards the prepended TCP header that hop1 wrote, and the $remote_addr variable reflects hop1's IP rather than the original client. Two additional directives complete the setup: real_ip_header proxy_protocol; instructs nginx to extract the real IP from the Proxy Protocol header, and set_real_ip_from <hop1_cidr>; scopes that extraction to traffic originating from the trusted hop1 address range. With both directives present, $remote_addr resolves to the original client IP throughout the request lifecycle, which means User-Agent filtering, geo-blocking, and access log entries all operate against accurate source data rather than hop1's IP.

TLS Termination and Redirect Logic

TLS termination on hop2 uses either Certbot-issued certificates or pre-provisioned certificates distributed via Ansible Vault. For Certbot, the task should call certbot certonly --nginx -d {{ domain }} with a creates: /etc/letsencrypt/live/{{ domain }}/fullchain.pem argument, which makes the task a no-op when the certificate already exists. The nginx server block then references ssl_certificate /etc/letsencrypt/live/{{ domain }}/fullchain.pem; and ssl_certificate_key /etc/letsencrypt/live/{{ domain }}/privkey.pem; directly. Redirect logic sits inside the location / block: proxy_pass http://{{ hop2_upstream }}; for transparent proxying, or return 301 https://{{ redirect_target }}$request_uri; for explicit redirect responses. For pre-provisioned certificates, an Ansible copy task writes the cert and key to defined paths, and the same ssl_certificate directives point at those paths instead.

Jinja2 Redirect Rule Templating

The same redirector role can serve completely different redirect profiles by externalising key parameters as role variables. A practical template structure parameterises {{ redirect_target }}, {{ response_code }}, and {{ allowed_ua_pattern }} so that User-Agent filtering, response behaviour, and upstream targets are all resolved at Ansible runtime rather than hardcoded. The nginx if ($http_user_agent !~* "{{ allowed_ua_pattern }}") { return {{ decoy_response_code }}; } block becomes a single template line that produces different filter logic per host group. Inventory group vars or host vars supply the per-engagement values, meaning one ansible-playbook invocation against different inventory groups deploys operationally distinct redirector profiles from a single reusable role.

Idempotency as a Design Requirement

Every task in a redirector playbook should be written with idempotency as an explicit constraint, not an afterthought. Using state: present for package installation, creates: guards on Certbot invocations, and handler-driven reloads rather than unconditional restarts means that re-running the playbook after a config change reports changed only on the tasks that actually modified state. A clean idempotency check is straightforward: apply the playbook once, then apply it a second time without changing any variables; the second run should return zero changed tasks. IaC Bazaar's verified Ansible modules ship with this constraint enforced by default, with static validation confirming that no task unconditionally triggers a service restart or rewrites a file that has not changed, keeping repeated playbook runs safe to execute in production without manual review.

Security Considerations for IaC-Managed Redirectors

Provisioning redirector infrastructure through Terraform and Ansible removes human error from the deployment process, but it simultaneously encodes any security mistakes into repeatable, version-controlled templates. A single misconfiguration in a module propagates identically across every environment where that module is applied.

Open Redirect Vulnerabilities in Proxy Configurations

Open redirect vulnerabilities in nginx-based redirectors typically originate from proxy directives that reflect user-supplied input without validation. A proxy_pass $host directive is the canonical example: when the Host header or a query parameter drives the upstream destination, an attacker can craft a request that forwards traffic to an arbitrary external endpoint, bypassing the intended routing logic entirely. This is classified under CWE-601 and is fully preventable through static analysis before deployment. Tools like checkov and ansible-lint can scan Terraform HCL and Ansible templates respectively, flagging variable interpolations inside proxy_pass directives as high-severity findings. Embedding these checks in a CI pipeline ensures that permissive proxy patterns are caught at the pull request stage rather than after production traffic is already flowing through the redirector.

Supply Chain Integrity of Third-Party IaC Modules

An unsigned Ansible role pulled from Ansible Galaxy or an unverified Terraform module from a public registry represents an uninspected artifact being applied directly to production infrastructure. A malicious actor who compromises a popular nginx role can insert a secondary proxy_pass target that silently mirrors traffic to an attacker-controlled endpoint, with no visible change to the role's declared behavior. The mitigation is cosign signature verification applied before any third-party module is executed. IaC Bazaar addresses this threat directly: every module in the catalog is cosign-signed and security-scanned prior to listing, giving infrastructure teams a cryptographically verifiable chain of custody from the module author to the point of deployment. Treating unsigned modules the same way you would treat an unsigned container image is the correct operational posture.

Firewall Misconfiguration in Two-Hop Security Groups

Terraform security group resources are among the most common sources of redirector security failures. A hop1 aws_security_group rule with an ingress block scoped to 0.0.0.0/0 on all ports eliminates the traffic-steering isolation that the two-hop architecture is specifically designed to create. Hop2 rules that expose port 22 or any management port publicly are equally problematic. The correct configuration scopes hop1 inbound rules to expected source CIDRs on the proxy port only, and restricts hop2 inbound rules to the hop1 static IP on the forwarding port exclusively.

Mutual TLS Between Hops and Centralized Log Shipping

For high-security deployments, hop2 should require a client certificate from hop1 using ssl_verify_client on in the nginx server block. Ansible provisions the certificate and key pair onto hop1 at configuration time, while Terraform generates the certificate content using tls_private_key and tls_self_signed_cert resources rendered as secrets. This ensures that even if hop2's IP is discovered, unauthenticated connections are rejected at the TLS handshake.

Observability is equally non-negotiable. Ephemeral compute instances destroyed after an operation take their local access logs with them unless those logs are shipped off-host in real time. Ansible roles managing redirector instances should include a filebeat or promtail task that begins forwarding nginx access logs to CloudWatch Logs, a Loki instance, or a SIEM forwarding target immediately after the nginx service starts. Without this, post-incident forensics and compliance audits have no log record to reconstruct, converting a recoverable security event into an unresolvable one.

Verified Edge Redirector Modules at IaC Bazaar

Verified Edge Redirector Modules at IaC Bazaar

The supply chain risk outlined in the previous section has a direct mitigation point: IaC Bazaar's module catalog includes CloudFront distribution modules, nginx Ansible roles, and Kubernetes Ingress modules that are statically validated, security-scanned, and cosign-signed before they reach your workstation. Static validation catches misconfigured redirect rules, open proxy conditions, and missing TLS termination blocks at the linting stage, before any resource touches a live environment. Security scanning adds a second pass that flags known CVEs in dependency packages bundled with Ansible roles. The result is a module that arrives with a documented, reproducible audit trail rather than an implicit trust assumption.

The per-engagement pricing model deserves specific attention for red team operators and short-cycle platform work. Each module is available starting at $29 with no subscription required. For a one-day engagement where the entire redirector stack will be torn down after the operation, paying a recurring SaaS fee to access a single nginx role makes no operational or financial sense. The transactional model aligns with how ephemeral infrastructure actually works: provision, operate, destroy, repeat.

The cosign signature attached to every module enables a verification step that most IaC workflows omit entirely. Before running terraform init or ansible-galaxy install, a team can verify the cryptographic signature offline, confirming that the module artifact has not been modified in transit between the registry and the deployment host. This matters in air-gapped or restricted network environments where supply chain integrity cannot be delegated to a CDN or registry TLS certificate alone.

Vizier, IaC Bazaar's orchestrator, sequences a complete two-hop redirector deployment as a single workflow: compute provisioning via Terraform, nginx configuration via Ansible, and DNS record creation in the correct dependency order. All three stages draw from the verified module catalog, so the integrity guarantees carry through the entire pipeline rather than applying only to individual modules in isolation.

Production-ready stacks for AWS and GKE extend this further by shipping pre-wired CloudFront and Ingress redirect configurations. Teams clone a stack, supply environment-specific parameters such as origin domain, listener port, and redirect status code, and deploy without writing redirect logic from scratch. The scaffolding handles resource wiring; the operator handles intent.

Conclusion and Next Steps

The four architecture patterns covered in this guide each resolve to a clear IaC ownership boundary. CloudFront redirect behaviors belong exclusively to Terraform via aws_cloudfront_distribution. Two-hop nginx redirectors split across Terraform for compute provisioning and Ansible for configuration management. Kubernetes Ingress and Gateway API HTTPRoutes are handled through terraform-provider-kubernetes with annotation blocks. Serverless edge redirects in Lambda@Edge combine Terraform resource declarations with packaged function artifacts. Knowing which tool owns which layer prevents configuration drift before it starts.

Unverified, hand-rolled redirect configurations remain a persistent supply chain liability. Open redirect vulnerabilities embedded in community modules, unsigned Ansible roles, and unscanned Terraform files carry the same risk regardless of whether they were authored internally or pulled from a public registry. Cosign-signed, security-scanned modules eliminate that ambiguity at intake rather than at incident review.

Your immediate action items are concrete: audit existing redirect infrastructure for unsigned configurations and open redirect patterns in allow-listed destination logic, migrate all redirect rules into version-controlled IaC with state backends, and apply ephemeral state lifecycle policies to any redirector with a defined operational window.

Browse IaC Bazaar's networking and security catalog for cosign-signed CloudFront distribution, nginx Ansible role, and Kubernetes Ingress redirect modules available for immediate download, no subscription required.

More from the blog