URL maps overview Stay organized with collections Save and categorize content based on your preferences.
Google Cloud Application Load Balancers and Cloud Service Mesh use a Google Cloudconfiguration resource called aURL map to route HTTP(S) requests to backendservices or backend buckets.
For example, with an external Application Load Balancer, you can use a single URL mapto route requests to different destinations based on the rulesconfigured in the URL map:
- Requests for
https://example.com/videogo to one backend service. - Requests for
https://example.com/audiogo to a different backend service.
- Requests for
https://example.com/imagesgo to a Cloud Storagebackend bucket.
- Requests for any other host and path combination go to a default backendservice.
URL maps are used with the following Google Cloud products:
- External Application Load Balancer (global, regional, and classicmodes)
- Internal Application Load Balancer (cross-region andregional modes)
- Cloud Service Mesh, whenCloud Service Mesh is deployed with the load balancing APIs
There are two types of URL map resources available: global and regional.
Global
urlMapsare used byglobal external Application Load Balancers, classic Application Load Balancers, cross-region internal Application Load Balancers,and Cloud Service Mesh.regionUrlMapsare used byregional external Application Load Balancers, regional internal Application Load Balancers, and Cloud Service Mesh.
The type of resource that you use depends on the product's load balancingscheme.
| Product | Load-balancing scheme | URL map resource type | Supported destinations |
|---|---|---|---|
| Global external Application Load Balancer | EXTERNAL_MANAGED | Global | Backend services, backend buckets |
| Classic Application Load Balancer | EXTERNAL | Global | Backend services, backend buckets |
| Regional external Application Load Balancer | EXTERNAL_MANAGED | Regional | Backend services |
| Cross-region internal Application Load Balancer | INTERNAL_MANAGED | Global | Backend services |
| Regional internal Application Load Balancer | INTERNAL_MANAGED | Regional | Backend services |
| Cloud Service Mesh | INTERNAL_SELF_MANAGED | Global | Backend services |
| Cloud Service Mesh | INTERNAL_SELF_MANAGED | Regional | Backend services |
Not all URL map features are available for all products. URL maps used withglobal external Application Load Balancers, regional external Application Load Balancers, internal Application Load Balancersand Cloud Service Mesh also support several advancedtraffic management features. For more information about these differences, seeLoad balancer feature comparison: Routing and trafficmanagement. Inaddition, regional URL maps can be a resource that's designated as a serviceinApp Hub applications.
How URL maps work
When a request arrives at the load balancer, the load balancer routes therequest to a particular backend service or a backend bucket based on the rulesdefined in the URL map.
A backend service represents a collection of backends, which are instances of anapplication or microservice. A backend bucket is aCloud Storagebucket, which is commonly used to hoststatic content, such as images.
For regional external Application Load Balancers, internal Application Load Balancers, and Cloud Service Mesh, possibledestinations are the following:
- Defaultbackend service
- Non-default backend service
Additionally, global external Application Load Balancers support the following:
- Defaultbackend bucket
- Non-default backend bucket
For example, assume that you have the following setup:
- One IP address:
- All requests to your organization go to the same IP address and the sameload balancer.
- Traffic is directed to different backend services based on the request URL.
- Two domains:
example.nethosts training videos.example.orghosts your organization website.
- Four sets of servers:
- One hosts your organization website (backend service:
org-site). - One hosts the overall training video website (backend service:
video-site). - One hosts high definition (HD) training videos (backend service:
video-hd). - One hosts standard definition (SD) training videos (backend service:
video-sd).
- One hosts your organization website (backend service:
You want the following to happen:
- Requests to
example.org(or any domain other thanexample.net) to go totheorg-sitebackend service. - Requests to
example.netthat don't match more specific paths to go to thevideo-sitebackend service. - Requests to
example.net/video/hd/*to go to thevideo-hdbackend service. - Requests to
example.net/video/sd/*to go to thevideo-sdbackend service.
A--path-rule for/video/* matches URIs such as/video/test1 and/video/test2. However, this path rule doesn't match the path/video.
If the load balancer receives a request with/../ in the URL, the loadbalancer transforms the URL by removing the path segment before the.., andresponds with the transformed URL. For example, when a request is sent forhttp://example.net/video/../abc, the load balancer responds with a 302redirect tohttp://example.net/abc. Most clients then react by issuing arequest to the URL returned by the load balancer (in this case,http://example.net/abc). This 302 redirection isn't logged inCloud Logging.
The URL map lets you set up this type of host and path-based routing.
Load balancer naming
For Application Load Balancers, the name of the load balancer is always the sameas the name of the URL map. The behavior for each Google Cloud interfaceis as follows:
- Google Cloud console. If you create an Application Load Balancer by using theGoogle Cloud console, the URL map is automatically assigned the same namethat you entered for the load balancer name.
- Google Cloud CLI or API. If you create an Application Load Balancer byusing the gcloud CLI or the API, you enter a name of your choicewhile creating the URL map. This URL map name is then reflected in theGoogle Cloud console as the name of the load balancer.
To learn about how naming works for Proxy Network Load Balancers andPassthrough Network Load Balancers, seeBackend services overview: Load balancernaming.
URL map components
A URL map is aset of Google Cloud configurationresources that direct requestsfor URLs to backend servicesor backend buckets. The URL map does so by using thehostname andpath portions for each URL it processes:
- Ahostname is the domain name portion of a URL; forexample, the hostname portion of the URL
http://example.net/video/hdisexample.net. - Apath is the portion of a URL following the hostname and optional portnumber; for example, the path portion of the URL
http://example.net/video/hdis/video/hd.
This diagram shows the structure of the load balancing configuration objectsin relation to each other.
Note: The diagram isn't intended to show the processing flow for requests.You control which backend servicesor backend buckets receive incoming requests by using thefollowing URL map configuration parameters:
Default backend service ordefault backend bucket. When you create aURL map, you must specify either a default backend service or a default backendbucket, but not both. This default represents the backend service or backendbucket to which Google Cloud directs requests for URLs with any hostname,unless there is an applicablehost rule.
Note: Backend buckets are not supported with internal Application Load Balancers andCloud Service Mesh.Host rule (
hostRules). A host rule directs requests sent to one or moreassociated hostnames to a singlepath matcher (pathMatchers). The hostnameportion of a URL is either exactly matched ormatched using regularexpressions against the set of the host rule's configuredhostnames. In a URL map host and path rule, if you omit the host, the rulematches any requested host. To direct requests forhttp://example.net/video/hdto a path matcher, you need a single host rulethat at least includes the hostnameexample.net. That same host rule couldalso handle requests for other hostnames, but it would direct them to the samepath matcher.If you need to direct requests to different path matchers, you must usedifferent host rules. Two host rules in a URL map can't include the same hostname.
It is possible to match all hostnames by specifying the wildcard character
*in the host rule. For example, for the URLshttp://example.org,http://example.net/video/hd, andhttp://example.com/audio, all threehostnamesexample.org,example.net, andexample.comcan be matched byspecifying*in the host rule. It is also possible to match a partialhostname by specifying the wildcard character*. For example, a host rule*.example.netis matched against both hostnamesnews.example.netandfinance.example.net.Port number. Different Application Load Balancers handle port numbersdifferently. In the case of the internal Application Load Balancer, you can use theHostrule parameter to specify a port number. For example, to direct
Note: The load balancer doesn't validate the value of the hostname in theURL. Clients can set arbitrary values for the hostname, for example bysetting theexample.netrequests for port 8080, set the host rule toexample.net:8080. In the case of theclassic Application Load Balancer, only the hostname in the URL is considered whenmatching a host rule. For example,example.netrequests for port 8080 andport 80 match the host ruleexample.net.Hostheader. You shouldn't use the hostname field to implementaccess control for your application.Path matcher (
pathMatchers). A path matcher is the configurationparameter referenced by a host rule. It defines the relationship between thepath portion of a URL and the backend service or backend bucket that shouldserve the request. A path matcher consists of two elements:Path matcher default backend service orpath matcher default backendbucket. For each path matcher, you must at least specify a defaultbackend service or default backend bucket, but not both. This defaultrepresents the backend service or backend bucket to whichGoogle Cloud directs requests for URLs whose hostnames match a hostrule associated with the path matcher, and whose URL paths don't match anypath rule in the path matcher.
Path rules. For each path matcher, you can specify one or more pathrules, which are key-value pairs mapping a URL path to a single backendservice or backend bucket.
Flexible pattern matching operators let you match multiple parts of a URLpath, including partial URLs and suffixes (file extensions), by usingwildcard syntax. These operators can be helpful when you need to routetraffic and execute rewrites based on complex URL paths. You can alsoassociate one or more path components with named variables and then referto those variables when rewriting the URL. With named variables, you canreorder and remove URL components before the request is sent to yourorigin. For details, seeWildcards, regular expressions, and dynamic URLsin path rules.
If you need more advanced routing capabilities, for example, if you wantto direct traffic for a unique URL to multiple services, you can use routerules instead of path rules.
Route rules. Route rules can be used as an alternative to path ruleswhen you need advanced traffic routing capabilities such as routingtraffic based on the URL path, HTTP headers, and query parameters.
You can configure route rules with flexible pattern matching operators andnamed variables. These operators can be helpful when you need to routetraffic and execute rewrites based on complex URL paths. For details, seeWildcards and pattern matching operators in path templates for routerules.
You can also configure route rules to be matched against regularexpressions that match the path, query parameters, or headers in theincoming request. For details, seeRegular expressions in routerules.
Hostname and host rule relationship
A hostname can only reference a single host rule.
A single host rule can process multiple hostnames.
Host rule and path matcher relationship
Multiple host rules can reference a single path matcher.
A host rule can only reference a single path matcher.
URL and backend relationship
Each unique URL is directed to only one backend service or backend bucket.Consequently:
Google Cloud uses the hostname portion of a URL to select a singlehost rule and its referenced path matcher.
When you use path rules in a path matcher, you cannot create more than onepath rule for the same path. For example, requests for
/videos/hdcannotbe directed to more than one backend service or backend bucket. Backendservices can have backend instance groups or backend network endpoint groups(NEGs) in different zones and regions, and you can create backend bucketsthat use Multi-Regional Storage classes.To direct traffic for a unique URL to multiple services, you can use routerules instead of path rules. If you configure the path matcher with routerules for header or parameter matches, a unique URL can be directed to morethan one backend service or bucket, based on the contents of headers orquery parameters on the URL.
Similarly for regional external Application Load Balancers and Cloud Service Mesh, weightedbackend services on route actions can direct the same URL to multiplebackend services or buckets, depending on the weights set on the weightedbackend service.
URL maps and protocols
You can use the same URL map, host rules, and path matchers to process both HTTPand HTTPS requests submitted by clients, as long as both a target HTTP proxy anda target HTTPS proxy reference the URL map.
Simplest URL map
The simplest URL map only has a default backend service or a default backendbucket. It contains no host rules and no path matchers. Either the defaultbackend service or the default backend bucket (whichever one you defined)handles all requested URLs.
If you define a default backend service, Google Cloud directs requests toits backend instance groups or backend NEGs according to the backend service'sconfiguration.
Order of operations
For a given hostname and path in a requested URL, Google Cloud uses thefollowing procedure to direct the request to the correct backend serviceor backend bucket, as configured in your URL map:
If the URL map doesnot contain a host rule for the URL's hostname,Google Cloud directs requests to the URL map's default backend serviceor default backend bucket, depending on which one you defined.
If the URL map contains a host rule that includes the URL's hostname, the pathmatcher referenced by that host rule is consulted:
If the path matcher contains a path rule thatexactly matches the URL'spath, Google Cloud directs requests to the backend service orbackend bucket for that path rule.
If the path matcher doesnot contain a path rule that exactly matchesthe URL's path, but does contain a path rule ending in
/*whose prefixmatches thelongest section of the URL's path, then Google Clouddirects requests to the backend service or backend bucket for that pathrule. For example, for the URL map containing two path matcher rules/video/hd/movie1and/video/hd/*, if the URL contains the exact path/video/hd/movie1, it is matched against that path rule.If neither of the previous conditions is true, Google Cloud directsrequests to the path matcher's default backend service or default backendbucket, depending on which one you defined.
URL map configuration constraints
The following sections describe certain configuration constraints for URL mapcomponents.
Regular expressions matchers in host and route rules
Preview
This product or feature is subject to the "Pre-GA Offerings Terms" in the General Service Terms section of theService Specific Terms. Pre-GA products and features are available "as is" and might have limited support. For more information, see thelaunch stage descriptions.
Host rules allow you to match the hostname portion of a URL against the setof the host rule's configured hostnames. You can choose to use either a specifichostname or a wildcard* in thehostRules[].hosts[] field to be matchedagainst the hostname in the incoming request.
Route rules allow you to define match rules that can match a regularexpression either in the path or in the query string or in a header in theincoming request. Route rules support the use of regular expressions for thefollowing URL map fields:
pathMatchers[].routeRules[].matchRules[].regexMatch: A regular expressionthat is used to match the path of the incoming request.pathMatchers[].routeRules[].matchRules[].headerMatches[].regexMatch: Aregular expression that contains a predicate that matches a header of theincoming request.pathMatchers[].routeRules[].matchRules[].queryParameterMatches[].regexMatch:A regular expression that contains a predicate that matches a query parameterof the incoming request.
A request is considered to have matched a routeRule when any of the matchRulesare satisfied. However predicates within a given matchRule haveAND semantics.That is, all predicates within a matchRule must match for the request to matchthe rule.
Additional usage notes:
Regular expressions are supported only for the following products:
- Regional internal Application Load Balancers
- Cross-region internal Application Load Balancers
- Regional external Application Load Balancers
Global and classic Application Load Balancers don't support regular expressions.
You must useRE2 syntax toconstruct your regular expressions. For the complete list of limitations andoperators permitted in URL maps, seeRE2 specifications for URLmaps.
Regular expression matching is expensive in terms of memory consumption andrequest processing latencies. If you choose to use regular expressionmatching, you must factor in the performance degradation when you plan yourdeployment. For example, if you have a URL map with a single regularexpression, you can expect the load balancer latency to increase by 100microseconds per request. If your URL map has 5 regular expressions to bematched, you can expect latency to increase by 200 microseconds per request.
Example #1: Use a regular expression to match path
The path is considered a match if it matches the regular expression specified byregexMatch after removing any query parameters and anchors supplied with theoriginal URL. For example, in the following sample URL maps, the route ruleregular expression,/videos/hd.*, would apply to a URL with the path/videos/hd-abcd?key=245.
defaultService:projects/example-project/global/backendServices/org-sitename:rule-match-url-maphostRules:-hosts:-'*'# Match any hostpathMatcher:video-matcher-hosts:-example.netpathMatcher:video-matcherpathMatchers:-name:video-matcher# Optional: default service for this path matcher if no routeRules matchdefaultService:projects/example-project/global/backendServices/video-siterouteRules:-priority:100000matchRules:-regexMatch:/videos/hd.*routeAction:weightedBackendServices:-backendService:projects/example-project/global/backendServices/video-hdweight:100Here is an explanation for each field of the sample URL map:
defaultService: Specifies the default backend service to useif no other rules in the URL map match the incoming request.name: Assigns the namerule-match-url-map to this URL map configuration.hostRules: Defines a list of rules for matching the host headerof incoming requests. The first rule matches any host (*) and directstraffic to thepathMatchernamedvideo-matcher. The second rulespecifically matches the hostexample.netand also directs traffic to thepath matcher namedvideo-matcher.pathMatchers: Defines a list of named path matchers.name: Defines a path matcher namedvideo-matcher.defaultService: Sets the default service for this path.matcher. This service is used if a request matches the host rule(s) pointingtovideo-matcher but doesn't match any of therouteRuleswithin it.routeRules: Contains a list of rules to match the URL path.priority: Sets the priority of this rule to 100000. Rules are evaluated inorder from lowest to highest priority number.matchRules: Contains the conditions for this route rule to be matched.regexMatch: This condition checks if the URL path matches the regularexpression/videos/hd.*(for example, "/videos/hd" and"/videos/hd-caching").routeAction: Specifies the action to take if all conditions inmatchRulesare met.weightedBackendServices: Distributes traffic among a list of backendservices based on weights.backendService: Specifies the backend service to route traffic to.weight: Assigns a weight of 100 to this backend service. Since it's theonly service in the list, it will receive 100% of the traffic that matchesthis routeRule.
The following URL map shows a similar example without using arouteAction.
defaultService:projects/example-project/global/backendServices/video-sitename:path-matcher-videosrouteRules:matchRules:-regexMatch:/videos/hd.*priority:100000service:projects/example-project/global/backendServices/video-hdExample #2: Use a regular expression to match headers
The header is considered a match if the value of the header matches the regularexpression specified byregexMatch. For example, in the following sample URLmap, the header name regular expression,.*Android.*-hd, would apply to arequest with the headerUser-Agent:123Androidabc-hd.
defaultService:projects/example-project/regions/us-central1/backendServices/default-backend-servicename:header-match-url-maphostRules:-hosts:-'*'# Match any hostpathMatcher:header-matcherpathMatchers:-name:header-matcher# Optional: default service for this path matcher if no routeRules matchdefaultService:projects/example-project/regions/us-central1/backendServices/default-backend-servicerouteRules:-priority:1matchRules:-headerMatches:-headerName:User-AgentregexMatch:.*Android.*-hd# This prefix match applies to the path part of the URL-prefixMatch:/video/# service: can be used instead of routeAction if no other actions are neededservice:projects/example-project/regions/us-central1/backendServices/video-backend-service# Alternatively, use routeAction to specify the service:# routeAction:# weightedBackendServices:# - backendService: projects/example-project/regions/us-central1/backendServices/video-backend-service# weight: 100Here is an explanation for each field of the sample URL map:
defaultService: Specifies the default backend service to useif no other rules in the URL map match the incoming request.name: Assigns the nameheader-match-url-map to this URL map configuration.hostRules: Defines a list of rules for matching the host header of incomingrequests. The rule matches any host ('*') and directs traffic to thepathMatchernamed header-matcher.pathMatchers: Defines a list of named path matchers.name: Defines a path matcher namedheader-matcher.defaultService: Sets the default service for this path matcher. This serviceis used if a request matches the host rule but doesn't match any of therouteRuleswithin this path matcher.routeRules: Contains a list of rules to match incoming requests based onheaders and paths.priority: Sets the priority of this rule to 1. Rules are evaluated in orderfrom lowest to highest priority number.matchRules: Contains a list of conditions that must all be true for therule to match.headerMatches: Specifies conditions based on request headers.headerName: Looks for the User-Agent header.regexMatch: Checks if the User-Agent header value matches the regularexpression.*Android.*-hd. This would match User-Agents indicating anAndroid device, with a string containing "-hd".prefixMatch: Set to/video/, this condition checks if the URL path startswith "/video/".service: If allmatchRulesconditions are met, traffic is directedto this backend service.- The commented-out
routeActionsection shows an alternative way to specifythe backend service, which would be necessary if you needed to configureother route actions like URL rewrites, header transformations, or weightedbackend services.
Example #3: Use a regular expression to match query parameters
The query parameter is considered a match if the value of the path with thequery parameters matches the regular expression specified byregexMatch. Forexample, in the following sample URL map, the query parameter regularexpression,/im.*/.*.html, would apply to a URL with query parameters such as/images/random_page.html?param1=param_value_123abc-hd.
defaultService:projects/example-project/regions/us-central1/backendServices/sample-bsname:query-match-url-maphostRules:-hosts:-'*'# Match any hostpathMatcher:query-matcherpathMatchers:-name:query-matcher# Optional: default service for this path matcher if no routeRules matchdefaultService:projects/example-project/regions/us-central1/backendServices/sample-bsrouteRules:-priority:1matchRules:-queryParameterMatches:-name:param1#parameter name in queryregexMatch:param_value_.*-hd# This regexMatch applies to the path part of the URL-regexMatch:/im.*/.*.html# Directs traffic to this service if all conditions in matchRules are metservice:projects/example-project/regions/us-central1/backendServices/sample-images-bsHere is an explanation for each field of the sample URL map:
hostRules: Adds a rule to match all hosts (*) and directs traffic to thepathMatchernamedquery-matcher.pathMatchers: Defines a path matcher namedquery-matcher.routeRules: Places the providedrouteRulesblock withinquery-matcher.priority: Sets the priority of this rule to 1. Rules are evaluated in orderfrom lowest to highest priority number.matchRules: Contains the conditions for therouteRules.queryParameterMatches: Checks if the query parameter named "param1"matches the regular expressionparam_value_.*-hd.regexMatch: The/im.*/.*.htmlregular expression applies to the path ofthe URL (for example, /images/random_page.html), before the query string.service: Specifies the backend service to use if all conditions within thematchRulesare true.
Wildcards, regular expressions, and dynamic URLs in path rules and prefix match
A path rule (
pathMatchers[].pathRules[]) can only include awildcard character (*) after aforward slash character (/). For example,/videos/*and/videos/hd/*are valid for path rules, but/videos*and/videos/hd*are not.Path rules don't use regular expressions or substring matching.PathTemplateMatch can use simplified pathmatching operators. For example, path rules for either
/videos/hdor/videos/hd/*don't apply to a URL with the path/video/hd-abcd.However, a path rule for/video/*does apply to that path.A prefix match (
pathMatchers[].routeRules[].matchRules[].prefixMatch)doesnot treat*as a wildcard character, but as a literal character.Path matchers (and URL maps in general) don't offer features that functionlike Apache's
<LocationMatch>directive. If you have an application thatgenerates dynamic URL paths that have a common prefix, such as/videos/hd-abcdand/videos/hd-pqrs, and you need to send requests made to those paths todifferent backend services, you might not be able to do that with aURL map. For cases containing only a few possible dynamic URLs, youmight be able to create a path matcher with a limited set of path rules.For more complex cases, you need to do path-based regular expressionmatching on your backends.
Wildcards and pattern matching operators in path templates for route rules
Flexible pattern matching operators let you match multiple parts of a URL path,including partial URLs and suffixes (file extensions), by using wildcard syntax.These operators can be helpful when you need to route traffic and executerewrites based on complex URL paths. You can also associate one or more pathcomponents with named variables and then refer to those variables when rewritingthe URL. With named variables, you can reorder and remove URL components beforethe request is sent to your origin.
Pattern matching with wildcards is supported only for the following products:
- Global external Application Load Balancer
- Regional external Application Load Balancer
- Regional internal Application Load Balancer
- Cross-region internal Application Load Balancer
- Cloud Service Mesh
The following example routes traffic for an eCommerce application that hasseparate services for cart information and user information.You can configurerouteRules with flexible pattern matching operators andnamed variables to send the user's unique ID to a user account details pageand the user's cart information to a cart processing service afterrewriting the URL.
pathMatchers: - name: cart-matcher routeRules: - description: CartService matchRules: - pathTemplateMatch: '/xyzwebservices/v2/xyz/users/{username=*}/carts/{cartid=**}' service: cart-backend priority: 1 routeAction: urlRewrite: pathTemplateRewrite: '/{username}-{cartid}/' - name: user-matcher routeRules: - description: UserService matchRules: - pathTemplateMatch: '/xyzwebservices/v2/xyz/users/*/accountinfo/*' service: user-backend priority: 1Here's what happens when a client requests/xyzwebservices/v2/xyz/users/abc@xyz.com/carts/FL0001090004/entries/SJFI38u3401nms?fields=FULL&client_type=WEB,which has both user information and cart information:
- The request path matches the
pathTemplateMatchwithin thecart-matcherpathMatcher. The{username=*}variable matchesabc@xyz.comand the{cartid=**}variable matchesFL0001090004/entries/SJFI38u3401nms. - The query parameters are split off from the path, the path is rewrittenbased on
pathTemplateRewrite, and the query parameters are appended tothe rewritten path. We must only use the same variables that we used todefine thepathTemplateMatchin ourpathTemplateRewrite. - The rewritten request is sent to
cart-backendwith the rewritten URL path:/abc@xyz.com-FL0001090004/entries/SJFI38u3401nms?fields=FULL&client_type=WEB.
The following happens when a client requests/xyzwebservices/v2/xyz/users/abc%40xyz.com/accountinfo/abc-1234 instead,which has only user and account information:
- The request path matches the
pathTemplateMatchwithin theuser-matcherpathMatcher. The first*matchesabc%40xyz.comand the second*matchesabc-1234. - The request is sent to
user-backend.
The following table outlines the syntax for path template patterns.
| Operator | Matches |
|---|---|
* | A single path segment, not including the surrounding path separator/ characters. |
** | Matches zero or more characters, including any path separator/ characters between multiple path segments. If other operators are included, the** operator must be the last operator. |
{name} or{name=*} | A named variable matching one path segment. Matches a single path segment, not including the surrounding path separator/ characters. |
{name=news/*} | A named variable explicitly matching two path segments:news and a* wildcard segment. |
{name=*/news/*} | A named variable matching three path segments. |
{name=**} | A named variable matching zero or more characters. If present, must be the last operator. |
When you use these operators for flexible pattern matching, keep theseconsiderations in mind:
- Multiple operators can be combined in a single pattern.
- Query parameters are split off from the path, the path is rewrittenbased on
pathTemplateRewrite, and the query parameters are appended tothe rewritten path. - Requests are not percent-encoding normalized. For example, a URL with apercent-encoded slash character (%2F) is not decoded into the unencoded form.
- Each variable name, such as
{segment}or{region}, can appear only once inthe same pattern. Multiple variables of the same name are invalid and arerejected. - Variable names are case-sensitive and must be valid identifiers. To check ifa variable name is valid, ensure that it matches the regular expression
^[a-zA-Z][a-zA-Z0-9_]*$.{API},{api}, and{api_v1}are all valid identifiers. They identifythree distinct variables.{1},{_api}, and{10alpha}are not valid identifiers.
- There's a limit of five operators per template pattern.
To execute an optional URL rewrite before the request is sent to the origin,you can use the same variables that you defined to capture a path.For example, you can reference, reorder, or omit variables in thepathTemplateRewrite field when definingurlRewrite.
When you use variables and operators for flexible pattern matching for URLrewrites, keep these considerations in mind:
- When rewriting a URL, you can omit variables if they're not required as partof the rewritten URL.
- Prior to any rewrites, you can identify the URL sent by the clientat your origin by inspecting response headers. The original client URL is populatedwith the
x-client-request-urlheader and thex-envoy-original-pathheader.
Example URL map workflow with an external Application Load Balancer
The following example illustratesthe order of operations for a URLmap. This example configures only the URL map for an existingclassic Application Load Balancer. For conceptual simplicity, it only uses backendservices; however, you can substitute backend buckets instead. To learn how tocreate the load balancer's other components, seeCreate aclassic Application Load Balancer.
For more information about creating and configuring URL maps with path matchersand host rules, see thegcloud compute url-maps createdocumentation.
Create a URL map for the load balancer and specify a default backend service.This example creates a URL map named
video-org-url-mapthat references anexisting backend service namedorg-site.gcloud compute url-maps create video-org-url-map \ --default-service=org-site
Create a path matcher named
video-matcherwith the followingcharacteristics:- The default backend service is
video-site, an existing backend service. - Add path rules that direct requests for the exact URL path
/video/hdor the URL path prefix/video/hd/*to an existing backend service namedvideo-hd. - Add path rules that direct requests for the exact URL path
/video/sdor the URL path prefix/video/sd/*to an existing backend service namedvideo-sd.
gcloud compute url-maps add-path-matcher video-org-url-map \ --path-matcher-name=video-matcher \ --default-service=video-site \ --path-rules=/video/hd=video-hd,/video/hd/*=video-hd,/video/sd=video-sd,/video/sd/*=video-sd
- The default backend service is
Create a host rule for the
example.nethostname that references thevideo-matcherpath matcher.gcloud compute url-maps add-host-rule video-org-url-map \ --hosts=example.net \ --path-matcher-name=video-matcher
Thevideo-org-url-map URL map should look like this:
gcloud compute url-maps describe video-org-url-map
creationTimestamp: '2021-03-05T13:34:15.833-08:00'defaultService: https://www.googleapis.com/compute/v1/projects/PROJECT_ID/global/backendServices/org-sitefingerprint: mfyJIT7Zurs=hostRules:- hosts: - '*' pathMatcher: video-matcher- hosts: - example.net pathMatcher: video-matcherid: '8886405179645041976'kind: compute#urlMapname: video-org-url-mappathMatchers:- defaultService: https://www.googleapis.com/compute/v1/projects/PROJECT_ID/global/backendServices/video-site name: video-matcher pathRules: - paths: - /video/hd - /video/hd/* service: https://www.googleapis.com/compute/v1/projects/PROJECT_ID/global/backendServices/video-hd - paths: - /video/sd - /video/sd/* service: https://www.googleapis.com/compute/v1/projects/PROJECT_ID/global/backendServices/video-sdselfLink: https://www.googleapis.com/compute/v1/projects/PROJECT_ID/global/urlMaps/video-org-url-map
Thevideo-org-url-map URL map directs requested URLs to backends in thefollowing way.
The following table explains the request processing shown in the preceding diagram.
| Hostname | URL paths | Selected backend service | Reason for selection |
|---|---|---|---|
Hostname:example.org and all other hostnamesdifferent fromexample.net | all paths | org-site | The hostname is not in any host rule of the URL map, so the request is directed to the URL map's default backend service. |
Hostname:example.net | /video/video/examples | video-site | The request goes to the default backend service because there is no path rule for/video/ or/video/*. The host rule forexample.net references a path matcher, but that path matcher does not have any path rules that would apply to these paths. |
Hostname:example.net | /video/hd/video/hd/movie1/video/hd/movies/movie2Other URLs that begin with /video/hd/* | video-hd | A host rule forexample.net references a path matcher whose path rules direct requests for URL paths that either exactly match/video/hd or that begin with/video/hd/* to thevideo-hd backend service. |
Hostname:example.net | /video/sd/video/sd/show1/video/sd/shows/show2Other URLs that begin with /video/sd/* | video-sd | A host rule forexample.net references a path matcher whose path rules direct requests for URL paths that either exactly match/video/sd or that begin with/video/sd/* to thevideo-sd backend service. |
URL redirects
AURL redirect redirects your domain's visitors from one URL to another.
Adefault URL redirect is not conditioned on matching any particular patternin the incoming request. For example, you might want to use a default URLredirect to redirectany hostname to a hostname of your choice.
There are several ways to create a URL redirect, as outlined in the followingtable.
| Method | Configuration |
|---|---|
| URL map's default URL redirect | Top-leveldefaultUrlRedirect |
| A path matcher's default URL redirect | pathMatchers[].defaultUrlRedirect[] |
| A path matcher's path rule's URL redirect | pathMatchers[].pathRules[].urlRedirect |
| A path matcher's route rule's URL redirect | pathMatchers[].routeRules[].urlRedirect |
Inside of adefaultUrlRedirect orurlRedirect,pathRedirect always worksas follows:
- The entire request path is replaced with the path you specify.
Inside of adefaultUrlRedirect orurlRedirect, how theprefixRedirect worksdepends on how you use it:
- If you use a
defaultUrlRedirect,prefixRedirectis effectively aprefix prepend because the matched path is always/. - If you use a
urlRedirectwithin a path matcher's route rule or pathrule,prefixRedirectis a prefixreplacement based on how the requestedpath was matchedas defined in the path rule or route rule.
Redirect examples
The following table provides some examples of redirect configurations. Theright-hand column shows the API configuration for a default URL redirect.
| You want | Accomplished using a default URL redirect |
|---|---|
| HTTP-to-HTTPS redirect Redirect http://host.name/path to https://host.name/path | kind: compute#urlMap name: web-map-http defaultUrlRedirect: httpsRedirect: True |
| HTTP-to-HTTPS + Host redirect Redirect http://any-host-name/path to https://www.example.com/path | kind: compute#urlMap name: web-map-http defaultUrlRedirect: httpsRedirect: True hostRedirect: "www.example.com" |
| HTTP-to-HTTPS + Host redirect + Full path redirect Redirect http://any-host-name/path to https://www.example.com/newPath | kind: compute#urlMap name: web-map-http defaultUrlRedirect: httpsRedirect: True hostRedirect: "www.example.com" pathRedirect: "/newPath" |
| HTTP-to-HTTPS + Host redirect + Prefix redirect Redirect http://any-host-name/originalPath to https://www.example.com/newPrefix/originalPath | kind: compute#urlMap name: web-map-http defaultUrlRedirect: httpsRedirect: True hostRedirect: "www.example.com" prefixRedirect: "/newPrefix" |
The following partial snippet annotates each API resource:
defaultUrlRedirect: redirectResponseCode: MOVED_PERMANENTLY_DEFAULT httpsRedirect: True # True if you want https://, false if you want http:// hostRedirect: "new-host-name.com" # Omit to keep the requested host pathRedirect: "/new-path" # Omit to keep the requested path; mutually exclusive to prefixRedirect prefixRedirect: "/newPrefix" # Omit to keep the requested path; mutually exclusive to pathRedirect stripQuery: False # True to omit everything in the URL after ? ...
What's next
To add, validate, test, list, or delete a URL map, seeUse URLmaps.
For information about routing rule maps with Cloud Service Mesh, seeCloud Service Mesh routing rule mapsoverview.
Except as otherwise noted, the content of this page is licensed under theCreative Commons Attribution 4.0 License, and code samples are licensed under theApache 2.0 License. For details, see theGoogle Developers Site Policies. Java is a registered trademark of Oracle and/or its affiliates.
Last updated 2025-12-15 UTC.