URL Rewriting

To rewrite a URL with tyk, you must specify the components of the URL to capture, and then the order in which to re-assemble the captured components.

Unlike other web servers, tyk uses a wide match to capture the URL and then a fixed regex to handle the restructuring, so as with other middleware components you must set a path to match on, the configuration looks like this in an API Definition:

"url_rewrites": [{
    "path": "match/me",
    "method": "GET",
    "match_pattern": "(w+)/(w+)",
    "rewrite_to": "my/service?value1=$1&value2=$2"
}],

path

The path to match, this can contain wildcards, so to match all sub-resources under match/, you could use match/{id}, the wildcard {id} is transformed into a wide regex ((.*)) to ensure that everything possible is captured. This is then discarded. The name of the group is irrelevant, it is only for your reference.

method

The method to match

match_pattern

This is the actual capture group to generate, this is a pure regex, in this case we are capturing two word groups.

rewrite_to

Each capture group you specify is designated with an index, and then made available in the rewrtite_to template, here $n will map against each value found in the capture group, so in the above example, the rewrite will be:

my/service?value1=match&value2=me

Context variables

As of version 2.2 Tyk also allows context variables to be injected into the regex using the $tyk_context. namespace instead of the numeric index.

The context variables that are available are:

  • request_data: If the inbound request contained any query data or form data, it will be available in this object, for the URL Rewrite, tyk will format this data as key:value1,value2,valueN;key:value1,value2 etc.
  • path_parts: The compoenents of the path, split on /, again these values are made available in the format of a comma delimited list
  • token: The inbound raw token (if bearer tokens are being used) of this user
  • path: The path that is being requested
  • remote_addr: The IP address of the connecting client
Was this article helpful to you? Yes No