2

Here is part of my nginx.conf:

    location ^~ /api/ {
        #resolver kube-dns.kube-system.svc.cluster.local valid=5s; #don't work
        resolver 10.244.64.10;
        set $loadurl http://gateway-service.default.svc.cluster.local:55558/;
        if ($http_namespace != "" ) {
            set $loadurl http://gateway-service.$http_namespace.svc.cluster.local:55558/;
        }
        proxy_pass $loadurl;
        proxy_set_header   Host             $proxy_host;
        proxy_set_header   X-Real-IP        $remote_addr;
        proxy_set_header   X-Forwarded-For  $proxy_add_x_forwarded_for;
        proxy_cookie_path / /;  
    }

The Nginx is running on Kubernetes.
I'm trying to configure proxy_pass according to the namespace in the header.

Such as: When I request http://localhost/api/auth/login with header namespace:test,
I want proxy_pass is http://gateway-service.test.svc.cluster.local:55558/auth/login.

Or header namespace is empty, then proxy_pass is http://gateway-service.default.svc.cluster.local:55558/auth/login

But now I always get 404, I'm confused!

So I try the below test,
Using a variable in ```proxy_pass`` is not working, I also got 404:

location ^~ /api/ {
    resolver 10.244.64.10;
    set $loadurl http://gateway-service.default.svc.cluster.local:55558/;
    proxy_pass $loadurl; 
}

When I write URI in proxy_pass, Nginx can proxy the request to the default namespace, and I got the right response:

location ^~ /api/ {
    proxy_pass http://gateway-service.default.svc.cluster.local:55558/; 
}

I stuck here for almost three days. Do you have any suggestions?

fatihyildizhan
  • 8,614
  • 7
  • 64
  • 88
Daiql
  • 84
  • 9
  • You need to remove the trailing `/` and add a `rewrite...break`. See [this answer](https://stackoverflow.com/questions/58163580/nginx-infinite-reload-when-adding-variable-in-proxy-pass/58164232#58164232). – Richard Smith Apr 15 '21 at 08:28

1 Answers1

1

@RichardSmith comment helped me!I should use rewrite.
The configeration below work fine for me.

location ^~ /api/ {
    resolver kube-dns.kube-system.svc.cluster.local; #It working
    if ($http_namespace != "" ) {
        rewrite ^/api(.*)$ $1 break;
        proxy_pass http://gateway-service.$http_namespace.svc.cluster.local:55558;
        break;
    }
    proxy_pass http://gateway-service.default.svc.cluster.local:55558/;
    proxy_set_header   Host             $proxy_host;
    proxy_set_header   X-Real-IP        $remote_addr;
    proxy_set_header   X-Forwarded-For  $proxy_add_x_forwarded_for;
    proxy_cookie_path / /;  
}

And resolver kube-dns.kube-system.svc.cluster.local; also working in kubernetes!

Daiql
  • 84
  • 9