[英]Dynamic proxy_pass according request header in Nginx
Here is part of my nginx.conf
:这是我的
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. Nginx 在 Kubernetes 上运行。
I'm trying to configure proxy_pass
according to the namespace
in the header.我正在尝试根据 header 中的
namespace
来配置proxy_pass
。
Such as: When I request http://localhost/api/auth/login
with header namespace:test
,如:当我使用 header
namespace:test
请求http://localhost/api/auth/login
时,
I want proxy_pass
is http://gateway-service.test.svc.cluster.local:55558/auth/login
.我想要
proxy_pass
是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
或者 header 命名空间为空,则
proxy_pass
为http://gateway-service.default.svc.cluster.local:55558/auth/login
But now I always get 404, I'm confused!但是现在我总是得到404,我很困惑!
So I try the below test,所以我尝试下面的测试,
Using a variable in ```proxy_pass`` is not working, I also got 404:在 ```proxy_pass`` 中使用变量不起作用,我也得到 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:当我在
proxy_pass
中写入 URI 时, Nginx 可以将请求代理到默认命名空间,并且我得到了正确的响应:
location ^~ /api/ {
proxy_pass http://gateway-service.default.svc.cluster.local:55558/;
}
I stuck here for almost three days.我在这里呆了将近三天。 Do you have any suggestions?
你有什么建议吗?
@RichardSmith comment helped me!I should use rewrite
. @RichardSmith 评论帮助了我!我应该使用
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;
和
resolver kube-dns.kube-system.svc.cluster.local;
also working in kubernetes!也在 kubernetes 中工作!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.