How to redirect custom subdomain of a domain to a single kubernetes service with subdomain as parameter/ path?

ε祈祈猫儿з 提交于 2021-01-29 11:08:46

问题


I have a requirement for a multitenant application where each tenant should be separated by sub domains like below

t1.example.com  
t2.example.com  
t3.example.com  
.  
.  
.  
tn.example.com

So there could be any number of tenants in this case. I have a Kubernetes Backend Service named myservice responsible for handling all those requests and they need to be identified based on their subdomain. e.g. if the request comes from tn.example.com then it needs to be redirected to the -> myservice/tn .

t2.example.com   -> myservice/t2  
t3.example.com   -> myservice/t3 and so on.

So here the subdomain name will be the path argument during redirection which will differentiate different subdomains from app perspective . I need to do this dynamically for any number of subdomains. How this can be achieved in Kubernetes Nginx ingress controller ?


回答1:


I'm afraid that Nginx Ingress cannot provide exactly what you need in easy and straightforward way. However, you can always use more advance features, like overriding Server/Location Block section with configuration snippet through annotation, and then use lua Block to extract subdomain and change the request URI to backend.

There was similar thread on Github, where user sanigo used configuration-snippet with lua block as workaround.

nginx.ingress.kubernetes.io/configuration-snippet: |
  location ~ ^/v2/ {
    set_by_lua_block $repo {
      local host = ngx.req.get_headers()["host"];
      local reg = "^(?<repo>[^.]+).*";
      local m = ngx.re.match(host, reg);
      return m['repo'];
    }
    rewrite ^/(.*)$ /repository/$repo/$1 last;
  }

Quick note: in this example <repo> acts exactly as a subdomain.



来源:https://stackoverflow.com/questions/64482736/how-to-redirect-custom-subdomain-of-a-domain-to-a-single-kubernetes-service-with

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!