Sub topic 6
Listeners and routing rules
This chapter assumes you know what an Application Load Balancer (ALB) and a Network Load Balancer (NLB) are, and that you can run AWS CLI commands. It also assumes you know basic HTTP: hosts, paths, headers and status codes. Target groups are covered in the next chapter. Here they are only the places where a listener sends traffic.
What a listener is
A listener is a process on a load balancer that checks for connection requests on a protocol and port you configure. Each load balancer has one or more listeners. Each listener decides what to do with the traffic it accepts.
- An ALB listener accepts HTTP or HTTPS. Its decisions are made per request.
- An NLB listener accepts TCP, UDP, TCP_UDP or TLS. Its decisions are made per connection.
Two listeners on the same load balancer cannot share a port. A common layout is port 80 for redirecting to HTTPS and port 443 for the real application.
Rules, conditions and actions
An ALB listener holds an ordered list of rules. Every rule has three parts:
- A priority, which is a number from 1 to 50000. The default rule has no number and is always evaluated last.
- One or more conditions, which say which requests match.
- One or more actions, which say what happens to a matching request.
The load balancer evaluates rules from the lowest priority number to the highest. It applies the first rule whose conditions all match and stops. If no rule matches, the default rule applies. Every listener has a default rule, and you cannot delete it.
Conditions
An ALB supports these condition types:
| Condition | Matches on | Example |
|---|---|---|
| `path-pattern` | The URL path | `/api/*` |
| `host-header` | The Host header | `admin.example.com` |
| `http-header` | A named header value | `X-Client: mobile` |
| `http-request-method` | The HTTP method | `POST` |
| `query-string` | Key/value pairs in the query string | `version=2` |
| `source-ip` | The client IP in CIDR form | `203.0.113.0/24` |
Within one condition, multiple values are combined with OR. Across different conditions in the same rule, all must match (AND). Wildcards are * for any number of characters and ? for one character. Matching is case-sensitive for paths and case-insensitive for host names. A rule can contain up to five wildcards across its condition values, so check the current quota page before building elaborate patterns.
Actions
| Action | Effect |
|---|---|
| `forward` | Sends the request to one target group, or to several with weights |
| `redirect` | Returns an HTTP 301 or 302 with a new location |
| `fixed-response` | Returns a status code and optional body without contacting a target |
| `authenticate-cognito`, `authenticate-oidc` | Authenticates the user, then continues to a later action |
A rule ends with one terminal action (forward, redirect or fixed-response). Authentication actions come before it.
Building a listener with rules
This example creates an HTTPS listener whose default rule returns 404. It then adds a rule that forwards /api/* to an API target group. The variables hold ARNs you created earlier.
aws elbv2 create-listener \
--load-balancer-arn "$ALB_ARN" \
--protocol HTTPS \
--port 443 \
--certificates CertificateArn="$CERT_ARN" \
--ssl-policy ELBSecurityPolicy-TLS13-1-2-2021-06 \
--default-actions '[{"Type":"fixed-response","FixedResponseConfig":{"StatusCode":"404","ContentType":"text/plain","MessageBody":"Not found"}}]'
aws elbv2 create-rule \
--listener-arn "$LISTENER_ARN" \
--priority 10 \
--conditions '[{"Field":"path-pattern","PathPatternConfig":{"Values":["/api/*"]}}]' \
--actions '[{"Type":"forward","TargetGroupArn":"'"$API_TG_ARN"'"}]'Certificates and TLS policies are covered in the TLS termination chapter. The point here is the shape of the rule: conditions and actions are both JSON lists.
Redirecting HTTP to HTTPS
Put the redirect in the default action of the port 80 listener, so every plain HTTP request is upgraded.
aws elbv2 create-listener \
--load-balancer-arn "$ALB_ARN" \
--protocol HTTP \
--port 80 \
--default-actions '[{"Type":"redirect","RedirectConfig":{"Protocol":"HTTPS","Port":"443","StatusCode":"HTTP_301"}}]'Use HTTP_302 while testing. Browsers cache a 301 aggressively, which makes mistakes hard to undo.
Weighted forwarding
A forward action can list several target groups with weights. This supports blue/green and canary releases. The weights below send about 90 percent of requests to the current version and 10 percent to the new one.
aws elbv2 modify-listener \
--listener-arn "$LISTENER_ARN" \
--default-actions '[{
"Type":"forward",
"ForwardConfig":{
"TargetGroups":[
{"TargetGroupArn":"'"$BLUE_TG_ARN"'","Weight":90},
{"TargetGroupArn":"'"$GREEN_TG_ARN"'","Weight":10}
]
}
}]'Weighting is probabilistic per request. It does not guarantee an exact ratio over a small number of requests. Enable target group stickiness in ForwardConfig if one user must stay on one version.
Managing rule order
Priorities must be unique within a listener. Leave gaps, such as 10, 20, 30, so you can insert rules later. You can reorder rules in one call.
aws elbv2 set-rule-priorities \
--rule-priorities RuleArn="$RULE_A_ARN",Priority=20 RuleArn="$RULE_B_ARN",Priority=10Order matters most when patterns overlap. Suppose /api/* is priority 10 and /api/admin/* is priority 20. The admin rule never runs, because every admin request already matched /api/*. Put the more specific rule at the lower number.
You can check the result by reading the rules back.
aws elbv2 describe-rules --listener-arn "$LISTENER_ARN" \
--query 'Rules[].[Priority,Conditions[0].Field,Actions[0].Type]' \
--output tableNetwork Load Balancer listeners
NLB listeners have no rules. Each listener has only a default action, normally a forward to one target group. There is no path or host routing, because the NLB does not parse HTTP. A TLS listener on an NLB terminates TLS, then forwards plain TCP or TLS to targets. To route by path on an NLB, put an ALB behind it or use separate ports and target groups.
Common errors
- Rules that never match because of order, as in the overlapping example above.
- A
path-patternof/apithat misses/api/users. Use/api/*, and add/apias a second value if both must match. - Forgetting that a listener on port 80 with a forward default action serves plain HTTP. Add the redirect if you want HTTPS only.
- A security group that does not allow the listener port. The listener exists, but clients time out.
- Weights that are all zero, or a target group with no healthy targets, which produce 503 responses.
Exercise
An ALB listener has rule 10 with condition path-pattern /shop/* forwarding to target group A, and rule 20 with conditions path-pattern /shop/* and http-header X-Beta: true forwarding to target group B. Beta users still reach group A. Why, and what is the fix?
Show answer
Rules are evaluated from the lowest priority number and the first match wins. Every request to /shop/* matches rule 10, so rule 20 is never reached. Give the more specific rule (the one with the header condition) a lower number than the general rule, for example priority 5, or swap the priorities with set-rule-priorities.
Exercise
You need an HTTP listener on port 80 to send all traffic to HTTPS. Which action type do you use, which listener holds it, and why use HTTP_302 while testing?
Show answer
Use a redirect action in the default action of the port 80 listener, with Protocol HTTPS, Port 443 and a StatusCode. HTTP_302 is safer for testing because browsers cache a 301 permanently, so a mistaken redirect keeps affecting clients after you fix it.