Advanced ALB Listener Rules with Terraform: HTTP Header Routing & Redirects

In this part of my ongoing Terraform AWS Application Load Balancer (ALB) series, we focus on implementing advanced listener rules specifically HTTP Header-Based Routing and smart redirection techniques using query string and host header conditions.
These patterns are especially helpful in scenarios like:
- Routing requests in multi-tenant environments
- Handling marketing query parameters
- Redirecting traffic from legacy domains to modern services
Let’s walk through the key changes introduced in this configuration.
🔁 1. HTTP Header-Based Routing
myapp1-rule = {
actions = [{
type = "weighted-forward"
target_groups = [{
target_group_key = "mytg1"
weight = 1
}]
stickiness = {
enabled = true
duration = 3600
}
}]
conditions = [{
http_header = {
http_header_name = "custom-header"
values = ["app-1", "app1", "my-app-1"]
}
}]
}
🔍 Explanation:
http_header
condition: Matches requests based on the value of a custom HTTP header.- Flexible matching: Accepts multiple possible values.
- Sticky sessions: Maintains session affinity by routing the same client to the same target group for 1 hour.
- Use Case: Ideal for multi-tenant APIs or separating environments like staging vs. production.
🔁 2. Query String-Based Redirect
my-redirect-query = {
priority = 3
actions = [{
type = "redirect"
status_code = "HTTP_302"
host = "rezaops.com"
path = "/aws-eks/"
protocol = "HTTPS"
}]
conditions = [{
query_string = {
key = "website"
value = "aws-eks"
}
}]
}
🔍 Explanation:
- Redirects any request with a query string like
?website=aws-eks
. - Sends the user to
https://rezaops.com/aws-eks/
. - HTTP 302: A temporary redirect that preserves the original method.
- Use Case: Great for marketing campaigns, tracking parameters, or simplified short links.
🔁 3. Host Header-Based Redirect
my-redirect-hh = {
priority = 4
actions = [{
type = "redirect"
status_code = "HTTP_302"
host = "rezaops.com"
path = "/legacy-redirect/"
protocol = "HTTPS"
}]
conditions = [{
host_header = {
values = ["legacy.example.rezaops.com"]
}
}]
}
🔍 Explanation:
- This rule looks at the
Host
header from the request. - If the subdomain matches
legacy.example.rezaops.com
, traffic is redirected to a consolidated path. - Use Case: Excellent for sunsetting subdomains or migrating legacy apps.
✅ What Stayed the Same
- Target groups
mytg1
andmytg2
: No change in health checks or port settings. - Instance attachments: Reused existing EC2 configurations using
aws_lb_target_group_attachment
.
This ensures full backward compatibility while extending functionality.
🧩 Closing
This update brings powerful customization to your ALB setup using HTTP headers, query parameters, and host headers to route and redirect users exactly where you need them.