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
Mock response middleware via the endpoint designer in the dashboard
A request to this endpoint gets redirected to the Google search website via a browser. However, a 301 Moved Permanently response is generated via an API client such as curl.
Result of a curl request to the endpoint
curl -X GET -I http://localhost:8080/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:
A snippet of a custom redirect virtual endpoint plugin
function customRedirectVirtualEndpointPlugin(request, session, config) {
log("Started: customRedirectVirtualEndpointPlugin");
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: customRedirectVirtualEndpointPlugin");
return TykJsResponse(responseObject, session.meta_data)
}
Writing your custom code within the pre-request plugin lifecycle should suffice for custom plugins.
Comments
0 comments
Please sign in to leave a comment.