AWS ALB HTTP Header-Based Routing and Advanced Redirects with Terraform
This week, I was exploring Terraform on AWS. I learned how to make my Application Load Balancer (ALB) route traffic using HTTP headers and how to add redirect rules.
Before this, we did a first setup where we used host-based routing for multiple apps behind one ALB. Now I improved it with header-based routing and redirects.
1) Listener rules with HTTP header-based routing
Here I route requests by checking a header named custom-header. If it matches some values, the rule forwards the request to a specific target group.
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:
- The rule looks at the HTTP header
custom-header. - If the value is
app-1,app1, ormy-app-1, the ALB forwards the request to target groupmytg1. - Stickiness keeps the same user on the same target for 3600 seconds (1 hour).
- I also created a similar rule for
mytg2with values likeapp-2,app2, andmy-app-2.
Why this is useful:
- Good for multi-tenant or API setups where clients send a custom header.
- You can split traffic to different backends without changing domains.
2) Redirect rules (query string and host header)
I added two redirect examples to show how flexible ALB rules can be.
A) Redirect by query string
my-redirect-query = {
priority = 3
actions = [{
type = "redirect"
status_code = "HTTP_302"
host = "rezaops.com"
path = "/dummy-query-redirect"
protocol = "HTTPS"
}]
conditions = [{
query_string = {
key = "website"
value = "aws-eks"
}
}]
}
Explanation:
- If the URL has
?website=aws-eks, the rule returns a 302 redirect tohttps://rezaops.com/dummy-query-redirect. - This is helpful for campaign or search links where you look for certain query parameters.
B) Redirect by host header
my-redirect-hh = {
priority = 4
actions = [{
type = "redirect"
status_code = "HTTP_302"
host = "rezaops.com"
path = "/dummy-host-header-redirect"
protocol = "HTTPS"
}]
conditions = [{
host_header = {
values = ["azure-aks11.rezaops.com"]
}
}]
}
Explanation:
- If the Host header equals
azure-aks11.rezaops.com, the ALB redirects to/dummy-host-header-redirectonrezaops.com. - This is useful when moving users from old subdomains to new pages.
What stayed the same
- Same ALB module and version.
- Target groups
mytg1andmytg2still use HTTP health checks. - I attach private EC2 instances with
aws_lb_target_group_attachment. - No changes to the base network and instances, so adding rules does not break the setup.
Summary
- I changed routing from host-based to header-based using the
custom-header. - I added redirect rules based on query strings and host headers.
- These features give granular control for multi-app and multi-tenant systems without changing the main infrastructure.