Functions (2)·续1
lookup_json_string
lookup_json_string(field String, key String | Integer, key String | Integer optional, ...): String
Returns the string value associated with the supplied key in field.
The field must be a string representation of a valid JSON document.
The key can be an attribute name, a zero-based position number in a JSON array, or a combination of these two options (as extra function parameters), while following the hierarchy of the JSON document to obtain a specific value.
Examples:
- Given the following JSON object contained in the
http.request.body.rawfield:
{ "company": "cloudflare", "product": "rulesets" }
Thenlookup_json_string(http.request.body.raw, "company") == "cloudflare"will returntrue. - Given the following nested object:
{ "network": { "name": "cloudflare" } }
Thenlookup_json_string(http.request.body.raw, "network", "name") == "cloudflare"will returntrue. - Given the following JSON array at the root level:
["other_company", "cloudflare"]
Thenlookup_json_string(http.request.body.raw, 1) == "cloudflare"will returntrue. - Given the following array in a JSON object attribute:
{ "networks": ["other_company", "cloudflare"] }
Thenlookup_json_string(http.request.body.raw, "networks", 1) == "cloudflare"will returntrue. - Given the following root-level array of JSON objects:
[{ "network": "other_company" }, { "network": "cloudflare" }]
Thenlookup_json_string(http.request.body.raw, 1, "network") == "cloudflare"will returntrue.
lower
lower(String): String
Converts a string field to lowercase. Only uppercase ASCII bytes are converted. All other bytes are unaffected.
For example, if http.host is "WWW.cloudflare.com", then lower(http.host) == "www.cloudflare.com" will return true.
regex_replace
regex_replace(source String, regular_expression String, replacement String): String
Replaces a part of a source string matched by a regular expression with a replacement string, returning the result. The replacement string can contain references to regular expression capture groups (for example, ${1} and ${2}), up to eight replacement references.
Examples:
- Literal match replace:
regex_replace("/foo/bar", "/bar$", "/baz") == "/foo/baz" - If there is no match, the input string does not change:
regex_replace("/x", "^/y$", "/mumble") == "/x" - Match is case-sensitive by default:
regex_replace("/foo", "^/FOO$", "/x") == "/foo" - When there are multiple matches, only one replacement occurs (the first one):
regex_replace("/a/a", "/a", "/b") == "/b/a" - Escape a
$in the replacement string by prefixing it with another$:
regex_replace("/b", "^/b$", "/b$$") == "/b$" - Replace with capture groups:
regex_replace("/foo/a/path", "^/foo/([^/]*)/(.*)$", "/bar/${2}/${1}") == "/bar/path/a/"
Create capture groups by putting part of the regular expression in parentheses. Then, reference a capture group using ${<NUMBER>} in the replacement string, where <NUMBER> is the number of the capture group.
You can only use the regex_replace() function once in an expression, and you cannot nest it with the wildcard_replace() function.
Note
Currently, the regex_replace() function is only available in rewrite expressions of Transform Rules and target URL expressions of dynamic URL redirects.
remove_bytes
remove_bytes(Bytes): Bytes
Returns a new byte array with all the occurrences of the given bytes removed.
For example, if http.host is "www.cloudflare.com", then remove_bytes(http.host, "\x2e\x77") will return "cloudflarecom".
remove_query_args
remove_query_args(field String, query_param1 String, query_param2 String, ...): String
Removes one or more query string parameters from a URI query string. Returns a string without the specified parameters.
The field must be one of the following:
http.request.uri.queryraw.http.request.uri.query
The field cannot be a literal value such as "search=foo&order=asc".
The remove_query_args() function will remove all specified parameters (as query_param1, query_param2, etc.) , including repeated occurrences of the same parameter.
The ordering of unaffected query parameters will be preserved.
Examples:
// If http.request.uri.query is "order=asc&country=GB":
remove_query_args(http.request.uri.query, "country") will return "order=asc"
remove_query_args(http.request.uri.query, "order") will return "country=GB"
remove_query_args(http.request.uri.query, "search") will return "order=asc&country=GB" (unchanged)
// If http.request.uri.query is "category=Foo&order=desc&category=Bar":
remove_query_args(http.request.uri.query, "order") will return "category=Foo&category=Bar"
remove_query_args(http.request.uri.query, "category") will return "order=desc"
Note
You can only use the remove_query_args() function in rewrite expressions of Transform Rules.
sha256
sha256(input String | Bytes): Bytes
Computes the SHA-256 cryptographic hash of the input string or byte array. Returns a 32-byte hash value.
Use this function to generate signed request headers, validate request integrity, or create secure tokens directly in rule expressions.
Examples:
sha256("my-token")
The example above returns a 32-byte hash that your origin can validate to authenticate requests.
You can combine sha256() with encode_base64() to create Base64-encoded signatures:
encode_base64(sha256("my-token"))
To create a signed header value from request attributes:
encode_base64(sha256(concat(to_string(ip.src), to_string(http.request.timestamp.sec), "my-secret-key")))
Notes
The sha256() function is available as an Enterprise add-on and requires a specific entitlement. Contact your account team to enable it.
You can only use the sha256() function in rewrite expressions of Transform Rules.
split
split(input String, separator String, limit Integer): Array<String>
Splits the input string into an array of strings by breaking the initial string at every occurrence of the separator string. The returned array will contain at most limit number of elements.
If you provide a limit value lower than the actual number of substrings in the split string, the last element of the returned array will contain the remainder of the string.
The separator must be a non-empty literal string.
The limit is mandatory, and it must be a literal integer between 1 and 128.
If input is nil, the returned value will be nil.
This function does the opposite of the join() function.
Examples:
# Split a comma-separated list of categories obtained from an HTTP request header.
# A) Consider the following HTTP request header:
x-categories: groceries,electronics,diy,auto
split(http.request.headers["x-categories"][0], ",", 64) will return ["groceries", "electronics", "diy", "auto"]
split(http.request.headers["x-categories"][0], ",", 3) will return ["groceries", "electronics", "diy,auto"]
# B) Consider the following HTTP request header:
x-categories: groceries,,electronics
split(http.request.headers["x-categories"][0], ",", 64) will return ["groceries", "", "electronics"]
Note
The split() function is only available in response header transform rules and Custom Error Rules.
starts_with
starts_with(source String, substring String): Boolean
Returns true when the source starts with a given substring. Returns false otherwise. The source cannot be a literal value (like "foo").
For example, if http.request.uri.path is "/blog/first-post", then starts_with(http.request.uri.path, "/blog") will return true.
substring
substring(field String | Bytes, start Integer, end Integer optional): String
Returns part of the field value (the value of a String or Bytes field) from the start byte index up to (but excluding) the end byte index. The first byte in field has index 0. If you do not provide the optional end index, the function returns the part of the string from start index to the end of the string.
The start and end indexes can be negative integer values, which allows you to access characters from the end of the string instead of the beginning.
Examples:
// If http.request.body.raw is "asdfghjk":
substring(http.request.body.raw, 2, 5) will return "dfg"
substring(http.request.body.raw, 2) will return "dfghjk"
substring(http.request.body.raw, -2) will return "jk"
substring(http.request.body.raw, 0, -2) will return "asdfgh"
to_string
to_string(Integer | Boolean | IP address): String
Returns the string representation of an Integer, Boolean, or IP address value.
Examples:
// If cf.bot_management.score is 5:
to_string(cf.bot_management.score) will return "5"
// If ssl is true:
to_string(ssl) will return "true"
Note
You can only use the to_string() function in rewrite expressions of Transform Rules and target URL expressions of dynamic URL redirects.
trim
trim(source String | Bytes, trim_set String optional): String | Bytes
Removes matching bytes from both ends of source. Bytes within the remaining value are unaffected.
The source must be a field or a function result. It cannot be a literal value.
By default, the function removes these ASCII whitespace bytes:
- Tab (
\x09) - Line feed (
\x0a) - Vertical tab (
\x0b) - Form feed (
\x0c) - Carriage return (
\x0d) - Space (
\x20)
The optional trim_set argument replaces the default whitespace set. It must be a constant string without duplicate bytes.
The function matches individual bytes rather than substrings or Unicode characters.
An empty trim_set string leaves source unchanged. Empty input, or input containing only matching bytes, returns an empty value.
If source is nil, the function returns nil. For details, refer to Missing values.
All HTTP products support this function on all plans.
For example, if http.request.headers["x-label"][0] is " hello world ", this expression returns "hello world":
trim(http.request.headers["x-label"][0])
To remove surrounding slashes, provide a custom byte set. If http.request.uri.path is "//blog/post//", this expression returns "blog/post":
trim(http.request.uri.path, "/")
trim_end
trim_end(source String | Bytes, trim_set String optional): String | Bytes
Removes matching bytes from the end of source. By default, it removes trailing ASCII whitespace.
If source is nil, the function returns nil.
All HTTP products support this function on all plans.
The source must be a field or a function result. It cannot be a literal value. The optional trim_set argument must be a constant string without duplicate bytes.
For default bytes and custom byte matching, refer to trim().
For example, if http.request.uri.path is "//blog/post//", this expression returns "//blog/post":
trim_end(http.request.uri.path, "/")
trim_start
trim_start(source String | Bytes, trim_set String optional): String | Bytes
Removes matching bytes from the start of source. By default, it removes leading ASCII whitespace.
If source is nil, the function returns nil.
All HTTP products support this function on all plans.
The source must be a field or a function result. It cannot be a literal value. The optional trim_set argument must be a constant string without duplicate bytes.
For default bytes and custom byte matching, refer to trim().
For example, if http.request.uri.path is "//blog/post//", this expression returns "blog/post//":
trim_start(http.request.uri.path, "/")
upper
upper(String): String
Converts a string field to uppercase. Only lowercase ASCII bytes are converted. All other bytes are unaffected.
For example, if http.host is"www.cloudflare.com", then upper(http.host) will return "WWW.CLOUDFLARE.COM".
url_decode
url_decode(source String, options String optional): String
Decodes a URL-formatted string defined in source, as in the following:
%20and+decode to a space character ().%E4%BDdecodes toä½.
The source must be a field, that is, it cannot be a literal string.
The options parameter is optional. You must provide any options as a single string wrapped in quotes, such as "r" or "ur". The available options are the following:
r: Applies recursive decoding. For example,%2520will be decoded twice (recursively) to a space character ().u: Enables Unicode percent decoding. The result will be encoded in UTF-8. For example,"%u2601"would be decoded to a cloud emoji (☁️) encoded in UTF-8 ("\xe2\x98\x81", with a size of 3 bytes).
