0

I want to implement a simple redirect using Kong's request-termination & response-transformer plugins. The plugins mostly works, but I have an issue with handling query parameters.

My configuration for the plugins is similar to this (note: I'm using Kong in DB-less mode):

services:
- name: my-redirects
  url: http://localhost:8080/
  routes:
  - name: redirect-route
    paths:
    - /context$
    - /$
  plugins:
  - name: request-termination
    config:
      status_code: 301
      message: Redirect to main page...
  - name: response-transformer
    config:
      add:
        headers:
        - Location:/context/

I want to obtain the following behaviour:

  • User visits http://localhost:8000/ -> redirected to /context/
  • User visits http://localhost:8000/context -> redirected to /context/
  • User visits http://localhost:8000/?param=value -> redirected to /context/?param=value
  • User visits http://localhost:8000/context?param=value -> redirected to /context/?param=value

Basically both / and /context requests should be redirected to /context/ (with a final slash) but query parameters should be preserved.

How can I modify the configuration:

add:
  headers:
  - Location:/context/

to include query parameters matched in the request? I expect to be able to do something like:

add:
  headers:
  - Location:/context/$query_params
GACy20
  • 949
  • 1
  • 6
  • 14
  • What about write your own plugin to handle that ? – Ôrel Jul 03 '21 at 12:19
  • @Ôrel This seems like one of the most basic functionalities ever. I can't believe there isn't some way to deal with this without having to write code in Lua. Anyway if you can give an example plugin go ahead and answer this question. – GACy20 Jul 05 '21 at 07:01

1 Answers1

0

What we are using to solve this on kong running in kubernetes is to use an ingress Exact rule coupled with a pre-function plugin. It should be easy to adapt it to the non-k8s yaml config:

apiVersion: networking.k8s.io/v1
kind: Ingress
metadata:
  name: foo-ingress-redirect
    konghq.com/plugins: foo-redirect
spec:
  ...
  rules:
    - host: myhost.example
      http:
        paths:
          - path: /foo/bar  # redirect /foo/bar to /foo/bar/ via plugin above
            pathType: Exact
            backend:
              ...

and then plugin:

apiVersion: configuration.konghq.com/v1
kind: KongPlugin
metadata:
  name: foo-redirect
plugin: pre-function
config:
  access:
    - kong.response.exit(301, '', {['Location'] = '/foo/bar/'})

You can also play with kong.request interface if you need to e.g. pass the original query params on the redirect.

It's a bit convoluted but also did not find a simpler way.

dlouzan
  • 675
  • 7
  • 16