table.lookup
Available inall subroutines.
Looks up the key key
in the table ID
. When the key is present, its
associated value will be returned. When the key is absent, a not set
string value is returned.
You can use table.contains
to check for the presence of a key.
If you plan to do a lookup of that key's value, consider combining
the calls into a single lookup to find the key's presence and the
stored value at the same time. For example:
# note this depends on using a header, not a STRING variableset req.http.x = table.lookup(t, "key");if (!req.http.x) { # equivalent to if (!table.contains(t, "key")) # no such key} else { # use the value of req.http.x}
This works because a not set
header compares false in conditions.
The condition above depends on using a header for the returned value
and not a local STRING variable. This is because a not set
value
is converted to an empty string when assigned to a STRING variable
and the empty string always compares true in conditions.
See VCL Types
for details of the type conversion.
When a third STRING argument is provided, the lookup function behaves as
it would normally, except when a key is absent, the default
value is
returned instead.
Examples
table geoip_lang { "US": "en-US", "FR": "fr-FR", "NL": "nl-NL",}if (!req.http.Accept-Language) { set req.http.Accept-Language = table.lookup(geoip_lang, client.geo.country_code, "en-US");}
table extension { "xhtml5": "xhtml", "html5": "html", "htm": "html", "aif": "aiff", "tif": "tiff", "jpg": "jpeg", "mpg": "mpeg",}
sub vcl_recv { # normalizing URL file extensions declare local var.ext STRING;
# lowercase for both the table key and for the default value set var.ext = std.tolower(req.url.ext); set var.ext = table.lookup(extension, var.ext, var.ext);}
Try it out
table.lookup
is used in the following code examples. Examples apply VCL to real-world use cases and can be deployed as they are, or adapted for your own service. See the full list of code examples for more inspiration.
Click RUN on a sample below to provision a Fastly service, execute the code on Fastly, and see how the function behaves.
Apply HTTP basic auth to private endpoints
Store username/password list in an edge dictionary, authorize user at the edge, reject requests that don't have correct credentials.
Ban bad IPs for a fixed period
Block a list of IP addresses from accessing your service and include an expiry time.
Redirect old URLs at the edge
Use a dictionary of URL mappings to serve your redirects at lightning speed.