如何通过Kong Ingress Controller将www域名重定向至非www域名
实现www.example.com到example.com的301重定向方案
方案一:使用Kong Ingress原生注解(最简实现)
先纠正你现有Ingress的语法错误——当前rules结构中,host和对应的http块属于同一规则的子项,你的写法将二者拆分为独立规则,会导致配置失效。修正后给www.example.com添加重定向注解即可实现需求:
apiVersion: networking.k8s.io/v1 kind: Ingress metadata: name: sonar annotations: konghq.com/strip-path: 'true' spec: ingressClassName: kong rules: - host: "www.example.com" http: paths: - path: / pathType: Prefix backend: service: name: my-sonarqube-sonarqube port: number: 9000 annotations: konghq.com/redirect-to: 'example.com' konghq.com/redirect-status-code: '301' - host: "example.com" http: paths: - path: / pathType: Prefix backend: service: name: my-sonarqube-sonarqube port: number: 9000
注解说明:
konghq.com/redirect-to:指定重定向目标域名konghq.com/redirect-status-code:设置重定向状态码,301为永久重定向(搜索引擎友好),302为临时重定向
方案二:使用KongPlugin实现灵活重定向(保留请求路径)
如果需要保留原请求的路径参数(比如www.example.com/test重定向到example.com/test),可以通过自定义KongPlugin实现:
- 创建重定向插件配置:
apiVersion: configuration.konghq.com/v1 kind: KongPlugin metadata: name: redirect-www-to-nonwww config: status_code: 301 uri: "$scheme://example.com$request_uri" plugin: redirect
- 修改Ingress关联该插件:
apiVersion: networking.k8s.io/v1 kind: Ingress metadata: name: sonar annotations: konghq.com/strip-path: 'true' spec: ingressClassName: kong rules: - host: "www.example.com" http: paths: - path: / pathType: Prefix backend: service: name: my-sonarqube-sonarqube port: number: 9000 annotations: konghq.com/plugins: "redirect-www-to-nonwww" - host: "example.com" http: paths: - path: / pathType: Prefix backend: service: name: my-sonarqube-sonarqube port: number: 9000
关于你之前ConfigMap配置无效的原因
Kong Ingress Controller不支持直接修改ConfigMap添加Nginx server块的方式配置规则,它的配置逻辑完全通过Kubernetes原生资源(Ingress、KongPlugin等)驱动,直接修改底层配置会被Controller覆盖,因此这种方式不会生效。
内容的提问来源于stack exchange,提问作者Zhakyp Zhoomart uulu
相关产品推荐
相关产品推荐

