How to append Nginx IP to X-Forwarded-For in Kubernetes Nginx Ingress Controller

Viewed 20302

I’’m wondering “How to append Nginx IP to X-Forwarded-For”

I added snippet in Ingress annotation.

apiVersion: networking.k8s.io/v1beta1
kind: Ingress
metadata:
  name: ing
  annotations:
    nginx.ingress.kubernetes.io/configuration-snippet: |
      proxy_set_header X-Forwarded-For "$remote_addr, $server_addr";

But it seems to double set in nginx.conf.

    proxy_set_header X-Forwarded-For        $remote_addr;
...
    proxy_set_header X-Forwarded-For "$remote_addr, $server_addr";

So my backend server will get two X-Forwarded-For

Anyone knows “How to disable the proxy_set_header part generated by Nginx Ingress Controller”?

        proxy_set_header X-Request-ID           $req_id;
        proxy_set_header X-Real-IP              $remote_addr;

        proxy_set_header X-Forwarded-For        $remote_addr;

        proxy_set_header X-Forwarded-Host       $best_http_host;
        proxy_set_header X-Forwarded-Port       $pass_port;
        proxy_set_header X-Forwarded-Proto      $pass_access_scheme;

        proxy_set_header X-Scheme               $pass_access_scheme;
3 Answers

Your configuration snippet is not being doubled, actually what is happening is that proxy_set_header X-Forwarded-For $remote_addr; is already set by default when you deploy NGINX Controller in your cluster.

In order to disable this default setting, you need to use a custom template.

By doing this, you can have a nginx.conf free of proxy_set_header X-Forwarded-For $remote_addr; so you can set it as you need using the annotation you have described.

The accepted answer is not worked for me. You just need to add the below annotation to the ingress object;

nginx.ingress.kubernetes.io/configuration-snippet: |
      more_set_headers "X-Forwarded-For $http_x_forwarded_for";

for testing;

❯ curl -I https://example.com/path/here

HTTP/1.1 200 OK
cache-control: no-cache, no-store, max-age=0, must-revalidate
Date: Sat, 13 Mar 2021 08:52:02 GMT
expires: 0
pragma: no-cache
vary: Origin,Access-Control-Request-Method,Access-Control-Request-Headers
X-Forwarded-For: 88.888.8.8
Connection: keep-alive

Just for people with a similar problem who end up here, an alternative (perhaps cleaner) solution, if you're deploying ingress-nginx controller using Helm is to set both compute-full-forwarded-for and use-forwarded-headers to true in your values.yml. No need for additional configurations in the Ingress (like the one in the question).

Related