Kubernetes NGINX 入口配置映射 301 重定向

Kubernetes NGINX Ingress configmap 301 redirect

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

我试过查看 configmap 文档,但看不到我需要的内容。也许它可以自己进入入口?

我也看过一个使用注释的例子,但这似乎是入口范围的,所以我不能为每个主机设置特定的重定向

确实可以通过简单的注释进行重定向:

但是正如您所提到的,它 "Ingress" 范围很广,并且不能针对每个主机、每个域甚至每个路径进行配置。所以你必须自己通过 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://.anotherdomain.com$request_uri;
      }
spec:
  rules:
  - host: ...

如果您还不太习惯 NGINX,您会更多地了解代码片段中的可能性,尤其是 the NGINX documentation.

中的 $host 变量是什么

无论使用 HTTP 还是 HTTPS,都将所有流量从 example.com 和 www.example.com 重定向到新域。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

我对注释有疑问 server-snippet。续订证书时,进程崩溃。当我删除注释时,更新证书成功。还有其他解决方案吗?例如,在单独的 pod 中创建重定向 301?

    apiVersion: networking.k8s.io/v1
    kind: Ingress
    metadata:
      annotations:
        cert-manager.io/cluster-issuer: letsencrypt-prod
        certmanager.k8s.io/cluster-issuer: letsencrypt-prod
        ingress.kubernetes.io/ssl-redirect: "true"
        meta.helm.sh/release-name: DOMAIN
        meta.helm.sh/release-namespace: DOMAIN
        nginx.ingress.kubernetes.io/configuration-snippet: |
          location ~ ^/online-web {
            return 301 /online;
          }
          if ($host = 'DOMAIN-alias.cz') {
            return 301 https://DOMAIN.cz;
          }
          if ($host ~ ^(.+)\.DOMAIN-alias\.cz$) {
            return 301 https://.DOMAIN.cz$request_uri;
          }
          if ($host = 'DOMAIN-alias-2.cz') {
            return 301 https://DOMAIN.cz;
          }
    nginx.ingress.kubernetes.io/force-ssl-redirect: "true"
    nginx.ingress.kubernetes.io/proxy-buffer-size: 128k
    nginx.ingress.kubernetes.io/server-snippet: |
      if ($host ~ "csas.woltair.cz") {
          return 301 https://woltair.cz/zakaznik/doporuceni;
      }
............
............
  - host: csas.woltair.cz
    http:
      paths:
      - backend:
          service:
            name: woltair-cz-fe
            port:
              number: 8080
        path: /zakaznik/doporuceni
        pathType: ImplementationSpecific