Rewriting hosts

Kong Ingress Controller provides two annotations for manipulating the Host header. These annotations allow for three different behaviours:

  • Preserve the user-provided Host header
  • Default to the Host of the upstream service
  • Explicitly set the Host header to a known value

Preserve the Host header

Kong Ingress Controller preserves the hostname in the request by default.

curl -H 'Host:kong.example' "$PROXY_IP/echo?details=true"
HTTP request details
---------------------
Protocol: HTTP/1.1
Host: kong.example
Method: GET
URL: /?details=true

The Host header in the request to the upstream matches the Host header in the request to Kong Gateway.

Use the upstream Host name

You can disable preserve-host if you want the Host header to contain the upstream hostname of your service.

Add the konghq.com/preserve-host annotation to your Route:

The Host header in the response now contains the upstream host and port.

HTTP request details
---------------------
Protocol: HTTP/1.1
Host: 192.168.194.11:1027
Method: GET
URL: /?details=true

Set the Host header explicitly

Using Gateway API v3.2+

You can set the Host header explicitly when using Gateway API’s HTTPRoute with URLRewrite filter’s hostname field. You only need to add a URLRewrite filter to your HTTPRoute rule.

...
filters:
- type: URLRewrite
  urlRewrite:
    hostname: internal.myapp.example.com

Using the konghq.com/host-header annotation

You can set the Host header explicitly if needed by disabling konghq.com/preserve-host and setting the konghq.com/host-header annotation.

  1. Add the konghq.com/preserve-host annotation to your Ingress, to disable preserve-host and send the hostname provided in the host-header annotation:

  2. Add the konghq.com/host-header annotation to your Service, which sets the Host header directly:

    kubectl patch service NAME -p '{"metadata":{"annotations":{"konghq.com/host-header":"internal.myapp.example.com"}}}'
    
  3. Make a curl request with a Host header:

    curl -H 'Host:kong.example' "$PROXY_IP/echo?details=true"
    

    The request upstream now uses the header from the host-header annotation:

    HTTP request details
    ---------------------
    Protocol: HTTP/1.1
    Host: internal.myapp.example.com:1027
    Method: GET
    URL: /?details=true
    
Something wrong?

Help us make these docs great!

Kong Developer docs are open source. If you find these useful and want to make them better, contribute today!