Kubernetes NGINX Ingress配置图301重定向

时间:2018-11-28 11:46:55

标签: kubernetes nginx-ingress

使用Kubernetes中的NGINX入口,我看不到一种方法,可以基于主机将流量从非www转发到www,或转发到另一个域等

我尝试查看configmap文档,但看不到我需要的东西。也许它可以进入入口本身?

我也看到了一个使用注释的示例,但这似乎是整个入口范围的,因此我无法对每个主机进行特定的重定向

2 个答案:

答案 0 :(得分:2)

实际上,可以使用简单的注释进行重定向:

但是正如您所提到的,它是“入口”的,不能按主机,按域甚至按路径配置。因此,您必须自己通过ingress.kubernetes.io/configuration-snippet注释来完成此操作,这要归功于正则表达式:

kind: Ingress
apiVersion: extensions/v1beta1
metadata:
  name: self-made-redirect
  annotations:
    ingress.kubernetes.io/configuration-snippet: |
      if ($host = 'blog.yourdomain.com') {
        return 301 https://yournewblogurl.com;
      }
      if ($host ~ ^(.+)\.yourdomain\.com$) {
        return 301 https://$1.anotherdomain.com$request_uri;
      }
spec:
  rules:
  - host: ...

如果您不习惯NGINX,您将进一步了解代码段中的可能功能,尤其是the NGINX documentation中的$host变量。

答案 1 :(得分:0)

要将所有流量(无论使用 HTTP 还是 HTTPS)从 example.com 和 www.example.com 重定向到 newdomain.example.com,我最终采用了以下解决方案。

在此示例中,我还使用 cert-manager.io 来请求 www.example.com 和 example.com 的证书。

使用注解 nginx.ingress.kubernetes.io/permanent-redirect

完成重定向
kind: Ingress
apiVersion: extensions/v1beta1
metadata:
  name: redirect-example-to-newdomain
  annotations:
    kubernetes.io/ingress.class: "nginx"
    cert-manager.io/cluster-issuer: "letsencrypt-prod"
    nginx.ingress.kubernetes.io/permanent-redirect: https://newdomain.example.com
spec:
  tls:
    - hosts:
      - example.com
      - www.example.com
      secretName: example.com-tls
  rules:
    - host: example.com
    - host: www.example.com