<p>Here is part of my <code>nginx.conf</code>:</p>
<pre><code>    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 != &quot;&quot; ) {
            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 / /;  
    }
</code></pre>
<p>The Nginx is running on Kubernetes.<br />
I'm trying to configure <code>proxy_pass</code> according to the <code>namespace</code> in the header.</p>
<p>Such as:
When I request <code>http://localhost/api/auth/login</code> with header <code>namespace:test</code>,<br />
I want <code>proxy_pass</code> is <code>http://gateway-service.test.svc.cluster.local:55558/auth/login</code>.</p>
<p>Or header namespace is empty, then <code>proxy_pass</code> is <code>http://gateway-service.default.svc.cluster.local:55558/auth/login</code></p>
<p>But now I always get 404, I'm confused!</p>
<p>So I try the below test,<br />
Using a variable in ```proxy_pass`` is not working, I also got 404:</p>
<pre><code>location ^~ /api/ {
    resolver 10.244.64.10;
    set $loadurl http://gateway-service.default.svc.cluster.local:55558/;
    proxy_pass $loadurl; 
}
</code></pre>
<p>When I write URI in <code>proxy_pass</code>, Nginx can proxy the request to the default namespace, and I got the right response:</p>
<pre><code>location ^~ /api/ {
    proxy_pass http://gateway-service.default.svc.cluster.local:55558/; 
}
</code></pre>
<p>I stuck here for almost three days. Do you have any suggestions?</p>

Daiql
<p>@RichardSmith comment helped me!I should use <code>rewrite</code>.<br />
The configeration below work fine for me.</p>
<pre><code>location ^~ /api/ {
    resolver kube-dns.kube-system.svc.cluster.local; #It working
    if ($http_namespace != &quot;&quot; ) {
        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 / /;  
}
</code></pre>
<p>And <code>resolver kube-dns.kube-system.svc.cluster.local;</code> also working in kubernetes!</p>
