It is possible to achieve a simple redirect in Tyk with a combination of relative path matching, mock response middleware and a location header. Here is a sample below
A request to this endpoint gets redirected to the Google search website via a browser. However, via an API client such as curl, a 301 Moved Permanently response is generated.
curl -X GET -I http://localhost:7070/redirect-api/fulcrum/next
HTTP/1.1 301 Moved Permanently
Location: http://google.com
Date: Thu, 11 May 2023 13:05:43 GMT
Content-Length: 0
You could compose a more complex redirect depending on your use case via the help of custom plugins e.g. the location header value needs a part of the URL path or even a part of the query string. An alternative to custom plugins could also be to use a virtual endpoint. I have attached a snipped below:
function customRedirectCustomVarPlugin(request, session, config) {
log("Started: customRedirectCustomVarPlugin");
log("Request: " + JSON.stringify(request))
log("URL: " + request.URL)
log("Params: " + JSON.stringify(request.Params))
locationHeader = "https://google.com/" + request.URL
var responseObject = {
Code: 301,
Headers: {
"Location": locationHeader
}
}
log("Finished: customRedirectCustomVarPlugin");
return TykJsResponse(responseObject, session.meta_data)
}
For custom plugins, writing your custom code within the pre-request plugin lifecycle should suffice.
Comments
0 comments
Please sign in to leave a comment.