

# Listener rules for your Application Load Balancer
<a name="listener-rules"></a>

The listener rules for your Application Load Balancer determine how it routes requests to targets. When a listener receives a request, it evaluates the request against each rule in priority order, starting with the lowest numbered rule. Each rule includes conditions to be met and the actions to perform when the conditions for the rule are met. This flexible routing mechanism allows you to implement sophisticated traffic distribution patterns, support multiple applications or microservices behind a single load balancer, and customize request handling based on your application's specific requirements.

**Rule basics**
+ Each rule consists of the following components: priority, actions, conditions, and optional transforms.
+ Each rule action has a type and the information required to perform the action.
+ Each rule condition has a type and the information required to evaluate the condition.
+ Each rule transform has a regular expression to match and a replacement string.
+ The regular expressions used in rule conditions and rule transforms do not support the following features: lookaheads, lookbehinds, backreferences, atomic groups, possessive quantifiers, subroutines, recursion, and Unicode character classes (such as `\p{L}`).
+ When you create a listener, you define actions for the default rule. The default rule can't have conditions or transforms. If none of the conditions for any other rules are met, then the action for the default rule is performed.
+ Rules are evaluated in priority order, from the lowest value to the highest value. The default rule is evaluated last. You can't change the priority of the default rule.
+ Each rule must include exactly one of the following actions: `forward`, `redirect`, or `fixed-response`, and it must be the last action to be performed.
+ Each rule other than the default rule can optionally include one of the following conditions: `host-header`, `http-request-method`, `path-pattern`, and `source-ip`. It can also optionally include one or both of the following conditions: `http-header` and `query-string`.
+ Each rule other than the default rule can optionally include one host header rewrite transform and one URL rewrite transform.
+ You can specify up to three comparison strings per condition and up to five per rule.

**Topics**
+ [Action types](rule-action-types.md)
+ [Condition types](rule-condition-types.md)
+ [Transforms](rule-transforms.md)
+ [Add a rule](add-rule.md)
+ [Edit a rule](edit-rule.md)
+ [Delete a rule](delete-rule.md)

# Action types for listener rules
<a name="rule-action-types"></a>

Actions determine how a load balancer handles requests when the conditions for a listener rule are satisfied. Each rule must have at least one action that specifies how to handle the matching requests. Each rule action has a type and configuration information. Application Load Balancers support the following action types for listener rules.Action types

`authenticate-cognito`  
[HTTPS listeners] Use Amazon Cognito to authenticate users. For more information, see [User authentication](listener-authenticate-users.md).

`authenticate-oidc`  
[HTTPS listeners] Use an identity provider that is compliant with OpenID Connect (OIDC) to authenticate users. For more information, see [User authentication](listener-authenticate-users.md).

`fixed-response`  
Return a custom HTTP response. For more information, see [Fixed-response actions](#fixed-response-actions).

`forward`  
Forward requests to the specified target groups. For more information, see [Forward actions](#forward-actions).

`jwt-validation`  
Validate JWT access tokens in client requests. For more information, see [JWT verification](listener-verify-jwt.md).

`redirect`  
Redirect requests from one URL to another. For more information, see [Redirect actions](#redirect-actions).

**Action basics**
+ Each rule must include exactly one of the following routing actions: `forward`, `redirect`, or `fixed-response`, and it must be the last action to be performed.
+ An HTTPS listener can have a rule with a user authentication action and a routing action.
+ When there are multiple actions, the action with the lowest priority is performed first.
+ If the protocol version is gRPC or HTTP/2, the only supported actions are `forward` actions.

## Fixed-response actions
<a name="fixed-response-actions"></a>

A `fixed-response` action drops client requests and returns a custom HTTP response. You can use this action to return a 2XX, 4XX, or 5XX response code and an optional message.

When a `fixed-response` action is taken, the action and the URL of the redirect target are recorded in the access logs. For more information, see [Access log entries](load-balancer-access-logs.md#access-log-entry-format). The count of successful `fixed-response` actions is reported in the `HTTP_Fixed_Response_Count` metric. For more information, see [Application Load Balancer metrics](load-balancer-cloudwatch-metrics.md#load-balancer-metrics-alb).

**Example fixed response action**  
You can specify an action when you create or modify a rule. For more information, see the [create-rule](https://docs.aws.amazon.com/cli/latest/reference/elbv2/create-rule.html) and [modify-rule](https://docs.aws.amazon.com/cli/latest/reference/elbv2/modify-rule.html) commands. The following action sends a fixed response with the specified status code and message body.  

```
[
  {
      "Type": "fixed-response",
      "FixedResponseConfig": {
          "StatusCode": "200",
          "ContentType": "text/plain",
          "MessageBody": "Hello world"
      }
  }
]
```

## Forward actions
<a name="forward-actions"></a>

A `forward` action routes requests to its target group. Before you add a `forward` action, create the target group and add targets to it. For more information, see [Create a target group](create-target-group.md).

**Distribute traffic to multiple target groups**  
If you specify multiple target groups for a `forward` action, you must specify a weight for each target group. Each target group weight is a value from 0 to 999. Requests that match a listener rule with weighted target groups are distributed to these target groups based on their weights. For example, if you specify two target groups, each with a weight of 10, each target group receives half the requests. If you specify two target groups, one with a weight of 10 and the other with a weight of 20, the target group with a weight of 20 receives twice as many requests as the other target group.

If you configure a rule to distribute traffic between weighted target groups and one of the target groups is empty or has only unhealthy targets, the load balancer does not automatically fail over to a target group with healthy targets.

**Sticky sessions and weighted target groups**  


By default, configuring a rule to distribute traffic between weighted target groups does not guarantee that sticky sessions are honored. To ensure that sticky sessions are honored, enable target group stickiness for the rule. When the load balancer first routes a request to a weighted target group, it generates a cookie named AWSALBTG that encodes information about the selected target group, encrypts the cookie, and includes the cookie in the response to the client. The client should include the cookie that it receives in subsequent requests to the load balancer. When the load balancer receives a request that matches a rule with target group stickiness enabled and contains the cookie, the request is routed to the target group specified in the cookie.

Application Load Balancers do not support cookie values that are URL encoded.

With CORS (cross-origin resource sharing) requests, some browsers require `SameSite=None; Secure` to enable stickiness. In this case, Elastic Load Balancing generates a second cookie, AWSALBTGCORS, which includes the same information as the original stickiness cookie plus this `SameSite` attribute. Clients receive both cookies.

### Example forward action with one target group
<a name="forward-action-cli"></a>

You can specify an action when you create or modify a rule. For more information, see the [create-rule](https://docs.aws.amazon.com/cli/latest/reference/elbv2/create-rule.html) and [modify-rule](https://docs.aws.amazon.com/cli/latest/reference/elbv2/modify-rule.html) commands. The following action forwards requests to the specified target group.

```
[
  {
      "Type": "forward",
      "ForwardConfig": {
          "TargetGroups": [
              {
                  "TargetGroupArn": "arn:aws:elasticloadbalancing:us-west-2:123456789012:targetgroup/my-targets/73e2d6bc24d8a067"
              }
          ]
      }
  }
]
```

### Example forward action with weighted target groups
<a name="forward-action-multiple-target-groups-cli"></a>

The following action forwards requests to the two specified target groups, based on the weight of each target group.

```
[
  {
      "Type": "forward",
      "ForwardConfig": {
          "TargetGroups": [
              {
                  "TargetGroupArn": "arn:aws:elasticloadbalancing:us-west-2:123456789012:targetgroup/blue-targets/73e2d6bc24d8a067",
                  "Weight": 10
              },
              {
                  "TargetGroupArn": "arn:aws:elasticloadbalancing:us-west-2:123456789012:targetgroup/green-targets/09966783158cda59",
                  "Weight": 20
              }
          ]
      }
  }
]
```

### Example forward action with stickiness enabled
<a name="forward-action-stickiness-cli"></a>

If you have a forward action with multiple target groups and one or more of the target groups has [sticky sessions](edit-target-group-attributes.md#sticky-sessions) enabled, you must enable target group stickiness.

The following action forwards requests to the two specified target groups, with target group stickiness enabled. Requests that do not contain the stickiness cookies are routed based on the weight of each target group.

```
[
  {
      "Type": "forward",
      "ForwardConfig": {
          "TargetGroups": [
              {
                  "TargetGroupArn": "arn:aws:elasticloadbalancing:us-west-2:123456789012:targetgroup/blue-targets/73e2d6bc24d8a067",
                  "Weight": 10
              },
              {
                  "TargetGroupArn": "arn:aws:elasticloadbalancing:us-west-2:123456789012:targetgroup/green-targets/09966783158cda59",
                  "Weight": 20
              }
          ],
          "TargetGroupStickinessConfig": {
              "Enabled": true,
              "DurationSeconds": 1000
          }
      }
  }
]
```

## Redirect actions
<a name="redirect-actions"></a>

A `redirect` action redirects client requests from one URL to another. You can configure redirects as either temporary (HTTP 302) or permanent (HTTP 301) based on your needs.

A URI consists of the following components:

```
protocol://hostname:port/path?query
```

You must modify at least one of the following components to avoid a redirect loop: protocol, hostname, port, or path. Any components that you do not modify retain their original values.

*protocol*  
The protocol (HTTP or HTTPS). You can redirect HTTP to HTTP, HTTP to HTTPS, and HTTPS to HTTPS. You cannot redirect HTTPS to HTTP.

*hostname*  
The hostname. A hostname is not case-sensitive, can be up to 128 characters in length, and consists of alpha-numeric characters, wildcards (\$1 and ?), and hyphens (-).

*port*  
The port (1 to 65535).

*path*  
The absolute path, starting with the leading "/". A path is case-sensitive, can be up to 128 characters in length, and consists of alpha-numeric characters, wildcards (\$1 and ?), & (using &amp;), and the following special characters: \$1-.\$1/\$1"'@:\$1.

*query*  
The query parameters. The maximum length is 128 characters.

You can reuse URI components of the original URL in the target URL using the following reserved keywords:
+ `#{protocol}` - Retains the protocol. Use in the protocol and query components.
+ `#{host}` - Retains the domain. Use in the hostname, path, and query components.
+ `#{port}` - Retains the port. Use in the port, path, and query components.
+ `#{path}` - Retains the path. Use in the path and query components.
+ `#{query}` - Retains the query parameters. Use in the query component.

When a `redirect` action is taken, the action is recorded in the access logs. For more information, see [Access log entries](load-balancer-access-logs.md#access-log-entry-format). The count of successful `redirect` actions is reported in the `HTTP_Redirect_Count` metric. For more information, see [Application Load Balancer metrics](load-balancer-cloudwatch-metrics.md#load-balancer-metrics-alb).

### Example redirect actions using the console
<a name="redirect-action-console"></a>

**Redirect using HTTPS and port 40443**  
The following rule sets up a permanent redirect to a URL that uses the HTTPS protocol and the specified port (40443), but retains the original hostname, path, and query parameters. This screen is equivalent to "https://\$1\$1host\$1:40443/\$1\$1path\$1?\$1\$1query\$1".

![\[A rule that redirects the request to a URL that uses the HTTPS protocol and the specified port (40443), but retains the original domain, path, and query parameters of the original URL.\]](http://docs.aws.amazon.com/elasticloadbalancing/latest/application/images/redirect_https_port.png)


**Redirect using a modified path**  
The following rule sets up a permanent redirect to a URL that retains the original protocol, port, hostname, and query parameters, and uses the `#{path}` keyword to create a modified path. This screen is equivalent to "\$1\$1protocol\$1://\$1\$1host\$1:\$1\$1port\$1/new/\$1\$1path\$1?\$1\$1query\$1".

![\[A rule that redirects the request to a URL that retains the original protocol, port, hostname, and query parameters, and uses the #{path} keyword to create a modified path.\]](http://docs.aws.amazon.com/elasticloadbalancing/latest/application/images/redirect_path.png)


### Example redirect actions using the AWS CLI
<a name="redirect-action-cli"></a>

**Redirect using HTTPS and port 40443**  
You can specify an action when you create or modify a rule. For more information, see the [create-rule](https://docs.aws.amazon.com/cli/latest/reference/elbv2/create-rule.html) and [modify-rule](https://docs.aws.amazon.com/cli/latest/reference/elbv2/modify-rule.html) commands. The following action redirects an HTTP request to an HTTPS request on port 443, with the same host name, path, and query string as the HTTP request.

```
  --actions '[{
      "Type": "redirect",
      "RedirectConfig": {
          "Protocol": "HTTPS",
          "Port": "443",
          "Host": "#{host}",
          "Path": "/#{path}",
          "Query": "#{query}",
          "StatusCode": "HTTP_301"
      }
  }]'
```

# Condition types for listener rules
<a name="rule-condition-types"></a>

Conditions define the criteria that incoming requests must meet for a listener rule to take effect. If a request matches the conditions for a rule, the request is handled as specified by the rule's actions. Each rule condition has a type and configuration information. Application Load Balancers support the following condition types for listener rules.Condition types

`host-header`  
Route based on the host name of each request. For more information, see [Host conditions](#host-conditions).

`http-header`  
Route based on the HTTP headers for each request. For more information, see [HTTP header conditions](#http-header-conditions).

`http-request-method`  
Route based on the HTTP request method of each request. For more information, see [HTTP request method conditions](#http-request-method-conditions).

`path-pattern`  
Route based on path patterns in the request URLs. For more information, see [Path conditions](#path-conditions).

`query-string`  
Route based on key/value pairs or values in the query strings. For more information, see [Query string conditions](#query-string-conditions).

`source-ip`  
Route based on the source IP address of each request. For more information, see [Source IP address conditions](#source-ip-conditions).

**Condition basics**
+ Each rule can optionally include zero or one of each of the following conditions: `host-header`, `http-request-method`, `path-pattern`, and `source-ip`. Each rule can also include zero or more of each of the following conditions: `http-header` and `query-string`.
+ With the `host-header`, `http-header`, and `path-pattern` conditions, you can use either value matching or regular expression (regex) matching.
+ You can specify up to three match evaluations per condition. For example, for each `http-header` condition, you can specify up to three strings to be compared to the value of the HTTP header in the request. The condition is satisfied if one of the strings matches the value of the HTTP header. To require that all of the strings are a match, create one condition per match evaluation.
+ You can specify up to five match evaluations per rule. For example, you can create a rule with five conditions where each condition has one match evaluation.
+ You can include wildcard characters in the match evaluations for the `http-header`, `host-header`, `path-pattern`, and `query-string` conditions. There is a limit of five wildcard characters per rule.
+ Rules are applied only to visible ASCII characters; control characters (0x00 to 0x1f and 0x7f) are excluded.
+ The regular expressions used in rule conditions do not support the following features: lookaheads, lookbehinds, backreferences, atomic groups, possessive quantifiers, subroutines, recursion, and Unicode character classes (such as `\p{L}`).

**Demos**  
For demos, see [Advanced request routing](https://exampleloadbalancer.com/advanced_request_routing_demo.html).

## Host conditions
<a name="host-conditions"></a>

You can use host conditions to define rules that route requests based on the host name in the host header (also known as *host-based routing*). This enables you to support multiple subdomains and different top-level domains using a single load balancer.

A hostname is not case-sensitive, can be up to 128 characters in length, and can contain any of the following characters:
+ A–Z, a–z, 0–9
+ - .
+ \$1 (matches 0 or more characters)
+ ? (matches exactly 1 character)

You must include at least one "." character. You can include only alphabetical characters after the final "." character.

**Example hostnames**
+ example.com
+ test.example.com
+ \$1.example.com

The rule \$1.example.com matches test.example.com but doesn't match example.com.

**Example host header condition**  
You can specify conditions when you create or modify a rule. For more information, see the [create-rule](https://docs.aws.amazon.com/cli/latest/reference/elbv2/create-rule.html) and [modify-rule](https://docs.aws.amazon.com/cli/latest/reference/elbv2/modify-rule.html) commands.  

```
[
  {
      "Field": "host-header",
      "HostHeaderConfig": {
          "Values": ["*.example.com"]
      }
  }
]
```

```
[
  {
      "Field": "host-header",
      "HostHeaderConfig": {
          "RegexValues": ["^(.*)\\.example\\.com$"]
      }
  }
]
```

## HTTP header conditions
<a name="http-header-conditions"></a>

You can use HTTP header conditions to configure rules that route requests based on the HTTP headers for the request. You can specify the names of standard or custom HTTP header fields. The header name and the match evaluation are not case-sensitive. The following wildcard characters are supported in the comparison strings: \$1 (matches 0 or more characters) and ? (matches exactly 1 character). Wildcard characters are not supported in the header name.

When the Application Load Balancer attribute `routing.http.drop_invalid_header_fields` is enabled, it will drop header names that don't conform to the regular expressions (`A-Z,a-z,0-9`). Header names that don't conform to the regular expressions can also be added.

**Example HTTP header condition**  
You can specify conditions when you create or modify a rule. For more information, see the [create-rule](https://docs.aws.amazon.com/cli/latest/reference/elbv2/create-rule.html) and [modify-rule](https://docs.aws.amazon.com/cli/latest/reference/elbv2/modify-rule.html) commands. The following condition is satisfied by requests with a User-Agent header that matches one of the specified strings.  

```
[
  {
      "Field": "http-header",
      "HttpHeaderConfig": {
          "HttpHeaderName": "User-Agent",
          "Values": ["*Chrome*", "*Safari*"]
      }
  }
]
```

```
[
  {
      "Field": "http-header",
      "HttpHeaderConfig": {
          "HttpHeaderName": "User-Agent",
          "RegexValues": [".+"]
      }
  }
]
```

## HTTP request method conditions
<a name="http-request-method-conditions"></a>

You can use HTTP request method conditions to configure rules that route requests based on the HTTP request method of the request. You can specify standard or custom HTTP methods. The match evaluation is case-sensitive. Wildcard characters are not supported; therefore, the method name must be an exact match.

We recommend that you route GET and HEAD requests in the same way, because the response to a HEAD request may be cached.

**Example HTTP method condition**  
You can specify conditions when you create or modify a rule. For more information, see the [create-rule](https://docs.aws.amazon.com/cli/latest/reference/elbv2/create-rule.html) and [modify-rule](https://docs.aws.amazon.com/cli/latest/reference/elbv2/modify-rule.html) commands. The following condition is satisfied by requests that use the specified method.  

```
[
  {
      "Field": "http-request-method",
      "HttpRequestMethodConfig": {
          "Values": ["CUSTOM-METHOD"]
      }
  }
]
```

## Path conditions
<a name="path-conditions"></a>

You can use path conditions to define rules that route requests based on the URL in the request (also known as *path-based routing*).

The path pattern is applied only to the path of the URL, not to its query parameters. It is applied only to visible ASCII characters; control characters (0x00 to 0x1f and 0x7f) are excluded.

The rule evaluation is performed only after URI normalization occurs.

A path pattern is case-sensitive, can be up to 128 characters in length, and can contain any of the following characters.
+ A–Z, a–z, 0–9
+ \$1 - . \$1 / \$1 " ' @ : \$1
+ & (using &amp;)
+ \$1 (matches 0 or more characters)
+ ? (matches exactly 1 character)

If the protocol version is gRPC, conditions can be specific to a package, service, or method.

**Example HTTP path patterns**
+ `/img/*`
+ `/img/*/pics`

**Example gRPC path patterns**
+ /package
+ /package.service
+ /package.service/method

The path pattern is used to route requests but does not alter them. For example, if a rule has a path pattern of `/img/*`, the rule forwards a request for `/img/picture.jpg` to the specified target group as a request for `/img/picture.jpg`.

**Example path pattern condition**  
You can specify conditions when you create or modify a rule. For more information, see the [create-rule](https://docs.aws.amazon.com/cli/latest/reference/elbv2/create-rule.html) and [modify-rule](https://docs.aws.amazon.com/cli/latest/reference/elbv2/modify-rule.html) commands. The following condition is satisfied by requests with a URL that contains the specified string.  

```
[
  {
      "Field": "path-pattern",
      "PathPatternConfig": {
          "Values": ["/img/*"]
      }
  }
]
```

```
[
  {
      "Field": "path-pattern",
      "PathPatternConfig": {
          "RegexValues": ["^\\/api\\/(.*)$"]
      }
  }
]
```

## Query string conditions
<a name="query-string-conditions"></a>

You can use query string conditions to configure rules that route requests based on key/value pairs or values in the query string. The match evaluation is not case-sensitive. The following wildcard characters are supported: \$1 (matches 0 or more characters) and ? (matches exactly 1 character).

**Example query string condition**  
You can specify conditions when you create or modify a rule. For more information, see the [create-rule](https://docs.aws.amazon.com/cli/latest/reference/elbv2/create-rule.html) and [modify-rule](https://docs.aws.amazon.com/cli/latest/reference/elbv2/modify-rule.html) commands. The following condition is satisfied by requests with a query string that includes either a key/value pair of "version=v1" or any key set to "example".  

```
[
  {
      "Field": "query-string",
      "QueryStringConfig": {
          "Values": [
            {
                "Key": "version", 
                "Value": "v1"
            },
            {
                "Value": "*example*"
            }
          ]
      }
  }
]
```

## Source IP address conditions
<a name="source-ip-conditions"></a>

You can use source IP address conditions to configure rules that route requests based on the source IP address of the request. The IP address must be specified in CIDR format. You can use both IPv4 and IPv6 addresses. Wildcard characters are not supported. You cannot specify the `255.255.255.255/32` CIDR for the source IP rule condition. 

If a client is behind a proxy, this is the IP address of the proxy, not the IP address of the client.

This condition is not satisfied by the addresses in the X-Forwarded-For header. To search for addresses in the X-Forwarded-For header, use an `http-header` condition.

**Example source IP condition**  
You can specify conditions when you create or modify a rule. For more information, see the [create-rule](https://docs.aws.amazon.com/cli/latest/reference/elbv2/create-rule.html) and [modify-rule](https://docs.aws.amazon.com/cli/latest/reference/elbv2/modify-rule.html) commands. The following condition is satisfied by requests with a source IP address in one of the specified CIDR blocks.  

```
[
  {
      "Field": "source-ip",
      "SourceIpConfig": {
          "Values": ["192.0.2.0/24", "198.51.100.10/32"]
      }
  }
]
```

# Transforms for listener rules
<a name="rule-transforms"></a>

A rule transform rewrites inbound requests before they are routed to targets. Rewriting a request does not change the routing decision made when evaluating the rule conditions. This is useful when clients send a different URL or host header than what the targets expect.

Using rule transforms offloads the responsibility for modifying paths, query strings, and host headers to the load balancer. This eliminates the need to add custom modification logic to your application code or rely on a third-party proxy to perform the modifications.

Application Load Balancers support the following transforms for listener rules.Transforms

`host-header-rewrite`  
Rewrites the host header in the request. The transform uses a regular expression to match a pattern in the host header and then replaces it with a replacement string.

`url-rewrite`  
Rewrites the request URL. The transform uses a regular expression to match a pattern in the request URL and then replaces it with a replacement string.

**Transform basics**
+ You can add one host header rewrite transform and one URL rewrite transform per rule.
+ You can't add a transform to a default rule.
+ If there is no pattern match, the original request is sent to the target.
+ If there is a pattern match but the transform fails, we return an HTTP 500 error.
+ The regular expressions used in rule transforms do not support the following features: lookaheads, lookbehinds, backreferences, atomic groups, possessive quantifiers, subroutines, recursion, and Unicode character classes (such as `\p{L}`).

## Host header rewrite transforms
<a name="host-header-rewrite-transforms"></a>

You can modify the domain name specified in the host header.

**Example host header transform**  
You can specify a transform when you create or modify a rule. For more information, see the [create-rule](https://docs.aws.amazon.com/cli/latest/reference/elbv2/create-rule.html) and [modify-rule](https://docs.aws.amazon.com/cli/latest/reference/elbv2/modify-rule.html) commands. The following is an example host header transform. It transforms the host header to an internal endpoint.  

```
[
  {
      "Type": "host-header-rewrite",
      "HostHeaderRewriteConfig": {
          "Rewrites": [
              {
                  "Regex": "^mywebsite-(.+).com$",
                  "Replace": "internal.dev.$1.myweb.com"
              }
          ]
      }
  }
]
```
For example, this transform rewrites the host header `https://mywebsite-example.com/project-a` as `https://internal.dev.example.myweb.com/project-a`.

## URL rewrite transforms
<a name="url-rewrite-transforms"></a>

You can modify the path or the query string of the URL. By rewriting the URL at the load balancer level, your frontend URLs can remain consistent for users and search engines even if your backend services change. You can also simplify complex URL query strings to make them easier for customers to type.

Note that you can't modify the protocol or port of the URL, only the path and the query string.

**Example URL rewrite transform**  
You can specify a transform when you create or modify a rule. For more information, see the [create-rule](https://docs.aws.amazon.com/cli/latest/reference/elbv2/create-rule.html) and [modify-rule](https://docs.aws.amazon.com/cli/latest/reference/elbv2/modify-rule.html) commands. The following is an example URL rewrite transform. It transforms the directory structure to a query string.  

```
[
  {
      "Type": "url-rewrite",
      "UrlRewriteConfig": {
          "Rewrites": [
              {
                  "Regex": "^/dp/([A-Za-z0-9]+)/?$",
                  "Replace": "/product.php?id=$1"
              }
          ]
      }
  }
]
```
For example, this transform rewrites the request URL `https://www.example.com/dp/B09G3HRMW` as `https://www.example.com/product.php?id=B09G3HRMW`.

**How URL rewrites differ from URL redirects**


| Characteristic | URL redirects | URL rewrites | 
| --- | --- | --- | 
| URL display | Changes in the browser address bar | No change in the browser address bar | 
| Status codes | Uses 301 (permanent) or 302 (temporary) | No status code change | 
| Processing | Browser-side | Server-side | 
| Common uses | Domain change, website consolidation, fixing broken links | Clean URLs for SEO, hide complex structures, provide legacy URL mapping | 

# Add a listener rule for your Application Load Balancer
<a name="add-rule"></a>

You define a default rule when you create a listener. You can define additional rules at any time. Each rule must specify an action and a condition, and can optionally specify transforms. For more information, see the following:
+ [Action types](rule-action-types.md)
+ [Condition types](rule-condition-types.md)
+ [Transforms](rule-transforms.md)

------
#### [ Console ]

**To add a rule**

1. Open the Amazon EC2 console at [https://console.aws.amazon.com/ec2/](https://console.aws.amazon.com/ec2/).

1. On the navigation pane, choose **Load Balancers**.

1. Select the load balancer.

1. On the **Listeners and rules** tab, select the text in the **Protocol:Port** column to open the detail page for the listener.

1. On the **Rules** tab, choose **Add rule**.

1. (Optional) To specify a name for your rule, expand **Name and tags** and enter the name. To add additional tags, choose **Add additional tags** and enter the tag key and tag value.

1. For each condition, choose **Add condition**, choose the condition type, and provide the required condition values:
   + **Host header** – Select the match pattern type and enter the host header.

     **Value matching** – Maximum 128 characters. Not case sensitive. Allowed characters are a-z, A-Z, 0-9; the following special characters: -\$1.; and wildcards (\$1 and ?). You must include at least one "." character. You can include only alphabetical characters after the final "." character.

     **Regex matching** – Maximum 128 characters.
   + **Path** – Select the match pattern type and enter the path.

     **Value matching** – Maximum 128 characters. Case sensitive. Allowed characters are a-z, A-Z, 0-9; the following special characters: \$1-.\$1/\$1"'@:\$1; &; and wildcards (\$1 and ?).

     **Regex matching** – Maximum 128 characters.
   + **Query string** – Enter key:value pairs, or values without keys.

     Maximum 128 characters. Not case sensitive. Allowed characters are a-z, A-Z, 0-9; the following special characters: \$1-.\$1/\$1"'@:\$1&()\$1,;=; and wildcards (\$1 and ?).
   + **HTTP request method** – Enter the HTTP request method.

     Maximum 40 characters. Case sensitive. Allowed characters are A-Z, and the following special characters: -\$1. Wildcards are not supported.
   + **HTTP header** – Select the match pattern type and enter the name of the header and the comparison strings.
     + **HTTP header name** – Rule will assess requests containing this header to confirm matching values.

       **Value matching** – Maximum 40 characters. Not case sensitive. Allowed characters are a-z, A-Z, 0-9, and the following special characters: \$1?-\$1\$1\$1%&'\$1.^\$1`\$1\$1. Wildcards are not supported.

       **Regex matching** – Maximum 128 characters.
     + **HTTP header value** – Enter strings to compare against the HTTP header value.

       **Value matching** Maximum 128 characters. Not case sensitive. Allowed characters are a-z, A-Z, 0-9; spaces; the following special characters: \$1"\$1\$1%&'()\$1,./:;<=>@[]^\$1`\$1\$1\$1\$1-; and wildcards (\$1 and ?).

       **Regex matching** – Maximum 128 characters.
   + **Source IP** – Define the source IP address in CIDR format. Both IPv4 and IPv6 CIDRs are allowed. Wildcards are not supported.

1. (Optional) To add a transform, choose **Add transform**, choose the transform type, and enter a regular expression to match and a replacement string.

1. (Optional, HTTPS listeners only) For **Pre-routing action**, select one of the following actions:
   + **Authenticate user** – Choose an identity provider and provide the required information. For more information, see [Authenticate users using an Application Load Balancer](listener-authenticate-users.md).
   + **Validate token** – Enter the JWKS endpoint, issues, and any additional claims. For more information, see [Verify JWTs using an Application Load Balancer](listener-verify-jwt.md).

1. For **Routing action**, select one of the following actions:
   + **Forward to target groups** – Choose a target group. To add another target group, choose **Add target group**, choose a target group, review the relative weights, and update the weights as needed. You must enable group-level stickiness if you enabled stickiness on any of the target groups.
   + **Redirect to URL** – Enter the URL by entering each part separately on the **URI parts** tab, or by entering the full address on the **Full URL** tab. For **Status code**, select either temporary (HTTP 302) or permanent (HTTP 301) based on your needs.
   + **Return fixed response** – Enter the **Response code** to return for dropped client requests. Optionally, you can specify the **Content type** and a **Response body**.

1. Choose **Next**.

1. For **Priority**, enter a value from 1-50,000. Rules are evaluated in priority order from the lowest value to the highest value.

1. Choose **Next**.

1. On the **Review and create** page, choose **Create**.

------
#### [ AWS CLI ]

**To add a rule**  
Use the [create-rule](https://docs.aws.amazon.com/cli/latest/reference/elbv2/create-rule.html) command.

The following example creates a rule with a `forward` action and a `host-header` condition.

```
aws elbv2 create-rule \
    --listener-arn listener-arn \
    --priority 10 \
    --conditions "Field=host-header,Values=example.com,www.example.com" \
    --actions "Type=forward,TargetGroupArn=target-group-arn"
```

To create a forward action that distributes traffic between two target groups, use the following `--actions` option instead.

```
    --actions '[{
        "Type":"forward",
        "ForwardConfig":{
          "TargetGroups":[
            {"TargetGroupArn":"target-group-1-arn","Weight":50},
            {"TargetGroupArn":"target-group-2-arn","Weight":50}
          ]
        }
    }]'
```

The following example creates a rule with a `fixed-response` action and a `source-ip` condition.

```
aws elbv2 create-rule \
    --listener-arn listener-arn \
    --priority 20 \
    --conditions '[{"Field":"source-ip","SourceIpConfig":{"Values":["192.168.1.0/24","10.0.0.0/16"]}}]' \
    --actions "Type=fixed-response,FixedResponseConfig={StatusCode=403,ContentType=text/plain,MessageBody='Access denied'}"
```

The following example creates a rule with a `redirect` action and an `http-header` condition.

```
aws elbv2 create-rule \
    --listener-arn listener-arn \
    --priority 30 \
    --conditions '[{"Field":"http-header","HttpHeaderConfig":{"HttpHeaderName":"User-Agent","Values":["*Mobile*","*Android*","*iPhone*"]}}]' \
    --actions "Type=redirect,RedirectConfig={Host=m.example.com,StatusCode=HTTP_302}"
```

------
#### [ CloudFormation ]

**To add a rule**  
Define a resource of type [AWS::ElasticLoadBalancingV2::ListenerRule](https://docs.aws.amazon.com/AWSCloudFormation/latest/TemplateReference/aws-resource-elasticloadbalancingv2-listenerrule.html).

The following example creates a rule with a `forward` action and a `host-header` condition. The rule sends traffic to the specified target group when the condition is met.

```
Resources:
    myForwardListenerRule:
     Type: 'AWS::ElasticLoadBalancingV2::ListenerRule'
     Properties:
       ListenerArn: !Ref myListener
       Priority: 10
       Conditions:
         - Field: host-header
           Values:
             - example.com
             - www.example.com
       Actions:
         - Type: forward
           TargetGroupArn: !Ref myTargetGroup
```

Alternatively, to create a forward action that distributes traffic between two target groups when the condition is met, define `Actions` as follows.

```
       Actions:
         - Type: forward
           ForwardConfig:
             TargetGroups:
               - TargetGroupArn: !Ref TargetGroup1
                 Weight: 50
               - TargetGroupArn: !Ref TargetGroup2
                 Weight: 50
```

The following example creates a rule with a `fixed-response` action and a `source-ip` condition.

```
Resources:
    myFixedResponseListenerRule:
     Type: 'AWS::ElasticLoadBalancingV2::ListenerRule'
     Properties:
       ListenerArn: !Ref myListener
       Priority: 20
       Conditions:
         - Field: source-ip
           SourceIpConfig:
             Values:
                - 192.168.1.0/24
                - 10.0.0.0/16
       Actions:
         - Type: fixed-response
           FixedResponseConfig:
             StatusCode: 403
             ContentType: text/plain
             MessageBody: "Access denied"
```

The following example creates a rule with a `redirect` action and an `http-header` condition.

```
Resources:
    myRedirectListenerRule:
     Type: 'AWS::ElasticLoadBalancingV2::ListenerRule'
     Properties:
       ListenerArn: !Ref myListener
       Priority: 30
       Conditions:
         - Field: http-header
           HttpHeaderConfig:
             HttpHeaderName: User-Agent
             Values: 
               - "*Mobile*"
               - "*Android*"
               - "*iPhone*"
       Actions:
         - Type: redirect
           RedirectConfig:
             Host: m.example.com
             StatusCode: HTTP_302
```

------

# Edit a listener rule for your Application Load Balancer
<a name="edit-rule"></a>

You can edit the action and conditions for a listener rule at any time. Rule updates do not take effect immediately, so requests could be routed using the previous rule configuration for a short time after you update a rule. Any in-flight requests are completed.

**Topics**
+ [Modify the default action](#modify-default-action)
+ [Update rule priorities](#update-rule-priority)
+ [Update actions, conditions, and transforms](#update-rule-actions-conditions-transforms)
+ [Manage the rule tags](#manage-rule-tags)

## Modify the default action
<a name="modify-default-action"></a>

The default action is assigned to a rule named **Default**. You can keep the current rule type and change the required information, or you can change the rule type and provide the new required information.

------
#### [ Console ]

**To modify the default action**

1. Open the Amazon EC2 console at [https://console.aws.amazon.com/ec2/](https://console.aws.amazon.com/ec2/).

1. On the navigation pane, choose **Load Balancers**.

1. Select the load balancer.

1. On the **Listeners and rules** tab, select the text in the **Protocol:Port** column to open the detail page for the listener.

1. On the **Rules** tab, in the **Listener rules** section, select the default rule. Choose **Actions**, **Edit rule**.

1. Under **Default action**, update the actions as needed.

------
#### [ AWS CLI ]

**To modify the default action**  
Use the [modify-listener](https://docs.aws.amazon.com/cli/latest/reference/elbv2/modify-listener.html) command. The following example updates the target group for the `forward` action.

```
aws elbv2 modify-listener \
    --listener-arn listener-arn \
    --default-actions Type=forward,TargetGroupArn=new-target-group-arn
```

The following example updates the default action to distribute traffic equally between two target groups.

```
aws elbv2 modify-listener \
    --listener-arn listener-arn \
    --default-actions '[{
      "Type":"forward",
      "ForwardConfig":{
        "TargetGroups":[
          {"TargetGroupArn":"target-group-1-arn","Weight":50},
          {"TargetGroupArn":"target-group-2-arn","Weight":50}
        ]
      }
    }]'
```

------
#### [ CloudFormation ]

**To modify the default action**  
Update the [AWS::ElasticLoadBalancingV2::Listener](https://docs.aws.amazon.com/AWSCloudFormation/latest/TemplateReference/aws-resource-elasticloadbalancingv2-listener.html) resource.

```
Resources:
    myHTTPlistener:
      Type: 'AWS::ElasticLoadBalancingV2::Listener'
      Properties:
        LoadBalancerArn: !Ref myLoadBalancer
        Protocol: HTTP
        Port: 80
        DefaultActions:
          - Type: "forward"
            TargetGroupArn: !Ref myNewTargetGroup
```

------

## Update rule priorities
<a name="update-rule-priority"></a>

Rules are evaluated in priority order, from the lowest value to the highest value. The default rule is evaluated last. You can change the priority of a nondefault rule at any time. You can't change the priority of the default rule.

------
#### [ Console ]

**To update rule priorities**

1. Open the Amazon EC2 console at [https://console.aws.amazon.com/ec2/](https://console.aws.amazon.com/ec2/).

1. In the navigation pane, choose **Load Balancers**.

1. Select the load balancer.

1. On the **Listeners and rules** tab, select the text in the **Protocol:Port** column to open the detail page for the listener.

1. On the **Rules** tab, select the listener rule and then choose **Actions**, **Reprioritize rules**.

1. In the **Listener rules** section, the **Priority** column displays the current rule priorities. To update a rule priority, enter a value from 1-50,000.

1. Choose **Save changes**.

------
#### [ AWS CLI ]

**To update rule priorities**  
Use the [set-rule-priorities](https://docs.aws.amazon.com/cli/latest/reference/elbv2/set-rule-priorities.html) command.

```
aws elbv2 set-rule-priorities \
    --rule-priorities "RuleArn=listener-rule-arn,Priority=5"
```

------
#### [ CloudFormation ]

**To update rule priorities**  
Update the [AWS::ElasticLoadBalancingV2::ListenerRule](https://docs.aws.amazon.com/AWSCloudFormation/latest/TemplateReference/aws-resource-elasticloadbalancingv2-listenerrule.html) resource.

```
Resources:
    myListenerRule:
     Type: 'AWS::ElasticLoadBalancingV2::ListenerRule'
     Properties:
       ListenerArn: !Ref myListener
       Priority: 5
       Conditions:
         - Field: host-header
           Values:
             - example.com
             - www.example.com
       Actions:
         - Type: forward
           TargetGroupArn: !Ref myTargetGroup
```

------

## Update actions, conditions, and transforms
<a name="update-rule-actions-conditions-transforms"></a>

You can update the actions, conditions, and transforms for a rule.

------
#### [ Console ]

**To update rule actions, conditions, and transforms**

1. Open the Amazon EC2 console at [https://console.aws.amazon.com/ec2/](https://console.aws.amazon.com/ec2/).

1. In the navigation pane, choose **Load Balancers**.

1. Select the load balancer.

1. On the **Listeners and rules** tab, select the text in the **Protocol:Port** column to open the detail page for the listener.

1. On the **Rules** tab, select the listener rule and then choose **Actions**, **Edit rule**.

1. Update the actions, conditions, and transforms as needed. For detailed steps, see [Add a rule](add-rule.md).

1. Choose **Next**.

1. (Optional) Update the priority.

1. Choose **Next**.

1. Choose **Save changes**.

------
#### [ AWS CLI ]

**To update rule actions, conditions, and transforms**  
Use the [modify-rule](https://docs.aws.amazon.com/cli/latest/reference/elbv2/modify-rule.html) command. Include at least one of the following options: `--actions`, `--conditions`, and `--transforms`.

For examples of these options, see [Add a rule](add-rule.md).

------
#### [ CloudFormation ]

**To update rule actions, conditions, and transforms**  
Update the [AWS::ElasticLoadBalancingV2::ListenerRule](https://docs.aws.amazon.com/AWSCloudFormation/latest/TemplateReference/aws-resource-elasticloadbalancingv2-listenerrule.html) resource.

For example rules, see [Add a rule](add-rule.md).

------

## Manage the rule tags
<a name="manage-rule-tags"></a>

Tags help you to categorize your listeners and rules in different ways. For example, you can tag a resource by purpose, owner, or environment. Tag keys must be unique for each rule. If you add a tag with a key that is already associated with the rule, it updates the value of that tag.

When you are finished with a tag, you can remove it.

------
#### [ Console ]

**To manage the tags for a rule**

1. Open the Amazon EC2 console at [https://console.aws.amazon.com/ec2/](https://console.aws.amazon.com/ec2/).

1. In the navigation pane, choose **Load Balancers**.

1. Choose the name of the load balancer to open its details page.

1. On the **Listeners and rules** tab, select the text in the **Protocol:Port** column to open the detail page for the listener.

1. On the **Rules** tab, select the text in the **Name tag** column to open the detail page for the rule.

1. On the rule details page, choose **Manage tags**.

1. On the **Manage tags** page, do one or more of the following:

   1. To add a tag, choose **Add new tag** and enter values for **Key** and **Value**.

   1. To delete a tag, choose **Remove** next to the tag.

   1. To update a tag, enter new values for **Key** or **Value**.

1. Choose **Save changes**.

------
#### [ AWS CLI ]

**To add tags to a rule**  
Use the [add-tags](https://docs.aws.amazon.com/cli/latest/reference/elbv2/add-tags.html) command.

```
aws elbv2 add-tags \
    --resource-arns listener-rule-arn \
    --tags "Key=project,Value=lima" "Key=department,Value=digital-media"
```

**To remove tags from a rule**  
Use the [remove-tags](https://docs.aws.amazon.com/cli/latest/reference/elbv2/remove-tags.html) command.

```
aws elbv2 remove-tags \
    --resource-arns listener-rule-arn \
    --tag-keys project department
```

------
#### [ CloudFormation ]

**To add tags to a rule**  
Update the [AWS::ElasticLoadBalancingV2::ListenerRule](https://docs.aws.amazon.com/AWSCloudFormation/latest/TemplateReference/aws-resource-elasticloadbalancingv2-listenerrule.html) resource.

```
Resources:
    myListenerRule:
     Type: 'AWS::ElasticLoadBalancingV2::ListenerRule'
     Properties:
       ListenerArn: !Ref myListener
       Priority: 10
       Conditions:
         - Field: host-header
           Values:
             - example.com
             - www.example.com
       Actions:
         - Type: forward
           TargetGroupArn: !Ref myTargetGroup
       Tags: 
        - Key: 'project'
          Value: 'lima'
        - Key: 'department'
          Value: 'digital-media'
```

------

# Delete a listener rule for your Application Load Balancer
<a name="delete-rule"></a>

You can delete the nondefault rules for a listener at any time. You can't delete the default rule for a listener. When you delete a listener, all its rules are deleted.

------
#### [ Console ]

**To delete a rule**

1. Open the Amazon EC2 console at [https://console.aws.amazon.com/ec2/](https://console.aws.amazon.com/ec2/).

1. On the navigation pane, choose **Load Balancers**.

1. Select the load balancer.

1. On the **Listeners and rules** tab, select the text in the **Protocol:Port** column to open the detail page for the listener.

1. Select the rule.

1. Choose **Actions**, **Delete rule**.

1. When prompted for confirmation, enter **confirm** and then choose **Delete**.

------
#### [ AWS CLI ]

**To delete a rule**  
Use the [delete-rule](https://docs.aws.amazon.com/cli/latest/reference/elbv2/delete-rule.html) command.

```
aws elbv2 delete-rule \
    --rule-arn listener-rule-arn
```

------