Search code examples
kongkong-plugin

Kong as redirection service


Is it possible to configure HTTP redirection rules in KONG (e.g if request matches ^/old-api/(.*)$ pattern then return 301 to https://other-domain.org/new-api/$1) without modifying nginx.conf templates (i.e. setup such rules using API and some plugin)?

What I am trying to achive is nginx equivalent of rewrite directive with redirect or permanent flag: http://nginx.org/en/docs/http/ngx_http_rewrite_module.html#rewrite


Solution

  • Edit: I found an even better answer now.

    Using the Serverless function plugin, it is possible to do a proper redirect with a Location header. The following Lua code should do that:

    kong.response.exit(301, 'page moved - redirecting...', {['Location'] = 'https://other-domain.org/' .. kong.request.get_path_with_query():gsub("%/old-api/", "/new-api/")})
    

    After that, the response looks like:

    # curl -i http://original-domain.org/old-api/abc
    HTTP/2 301
    date: Sat, 09 Jan 2021 17:03:04 GMT
    location: https://other-domain.org/new-api/abc
    content-length: 28
    x-kong-response-latency: 7
    
    page moved - redirecting...
    

    Original Answer:

    You can use your regular expressions and capturing groups in the route definition to save the path (or part of it) in a variable:

    ^/old-api/(?<path>.*)$
    

    Regrettably, the Response Transformer cannot simply use the path variable to create a Location: https://other-domain.org/new-api/$(uri_captures.<path>) header, like the Request Transformer Plugin can (see https://konghq.com/blog/url-rewriting-in-kong).

    If you only want to redirect a html page, you can at least make the route respond with code 301 by using the Request Termination Plugin and set status_code=301. You can also return text/html mime-type and return

    <script>location.href = 'https://other-domain.org/new-api/' + location.pathname.replace(/^\/old-api/, '/new-api')</script>
    

    in the body to circumvent this restriction.

    An alternative would be to implement a Kong Plugin yourself (I don't know about an existing one other than a very rudimentary one, https://github.com/domecloud/kong-plugin-redirect, which might be extended).

    PS: I just found another promising plugin which seems to be more powerful, though I didn't test it yet.