【问题标题】:Dynamic proxy_pass according request header in Nginx根据 Nginx 中的请求标头动态 proxy_pass
【发布时间】:2021-07-10 03:55:51
【问题描述】:

这是我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 / /;  
    }

Nginx 在 Kubernetes 上运行。
我正在尝试根据标题中的namespace 配置proxy_pass

如: 当我请求带有标题namespace:testhttp://localhost/api/auth/login 时,
我想要proxy_passhttp://gateway-service.test.svc.cluster.local:55558/auth/login

或者标头命名空间为空,则proxy_passhttp://gateway-service.default.svc.cluster.local:55558/auth/login

但现在我总是得到 404,我很困惑!

所以我尝试以下测试,
在 ```proxy_pass`` 中使用变量不起作用,我也得到了 404:

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

当我在proxy_pass 中写入URI 时,Nginx 可以将请求代理到默认命名空间,并且我得到了正确的响应:

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

我在这里呆了将近三天。你有什么建议吗?

【问题讨论】:

  • 您需要删除结尾的/ 并添加rewrite...break。见this answer
  • @RichardSmith 谢谢,重写确实有效!

标签: nginx kubernetes nginx-reverse-proxy nginx-config


【解决方案1】:

@RichardSmith 评论帮助了我!我应该使用rewrite
下面的配置对我来说很好。

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 / /;  
}

还有 resolver kube-dns.kube-system.svc.cluster.local; 也在 kubernetes 中工作!

【讨论】:

    猜你喜欢
    • 2018-02-27
    • 1970-01-01
    • 1970-01-01
    • 2018-10-30
    • 2019-03-14
    • 1970-01-01
    • 2012-06-22
    • 2013-11-03
    • 1970-01-01
    相关资源
    最近更新 更多