Kubernetes中非www转www重定向时避免查询参数重复的方法
解决查询参数重复的重定向问题
问题出在你使用的rewrite指令搭配$request_uri的方式:Nginx的rewrite规则会自动将原始请求的查询参数追加到目标URL后,而$request_uri本身已经包含了完整的路径和查询参数,最终导致参数重复。
修复方案
将configuration-snippet中的重定向逻辑替换为以下两种写法之一,避免重复追加参数:
推荐写法(使用return,更高效)
替换原有的configuration-snippet内容:
nginx.ingress.kubernetes.io/configuration-snippet: | if ($host = 'example.nl' ) { return 301 https://www.example.nl$uri$is_args$args; }
$uri:仅包含请求路径(不含查询参数)$is_args:如果存在查询参数则为?,否则为空字符串$args:原始请求的查询参数内容
替代写法(调整rewrite语法)
如果坚持使用rewrite,可以改为:
nginx.ingress.kubernetes.io/configuration-snippet: | if ($host = 'example.nl' ) { rewrite ^(.*)$ https://www.example.nl$1 permanent; }
这里$1捕获的是路径部分,Nginx不会自动追加查询参数,从而避免重复。
修改后的完整Ingress配置示例
apiVersion: networking.k8s.io/v1 kind: Ingress metadata: name: app-ingress annotations: service.beta.kubernetes.io/do-loadbalancer-name: "example" kubernetes.io/ingress.class: nginx cert-manager.io/cluster-issuer: letsencrypt-prod nginx.ingress.kubernetes.io/backend-protocol: HTTP nginx.ingress.kubernetes.io/configuration-snippet: | if ($host = 'example.nl' ) { return 301 https://www.example.nl$uri$is_args$args; } nginx.ingress.kubernetes.io/server-snippet: | gzip on; gzip_disable "msie6"; gzip_vary on; gzip_proxied any; gzip_comp_level 6; gzip_buffers 16 8k; gzip_http_version 1.1; gzip_min_length 256; gzip_types application/atom+xml application/geo+json application/javascript application/x-javascript application/json application/ld+json application/manifest+json application/rdf+xml application/rss+xml application/xhtml+xml application/xml font/eot font/otf font/ttf image/svg+xml text/css text/javascript text/plain text/xml; spec: tls: - hosts: - www.example.nl - example.nl secretName: main-example-tls rules: - host: www.example.nl http: paths: - path: / pathType: Prefix backend: service: name: front-end port: number: 3000 - path: /api pathType: Prefix backend: service: name: back-end port: number: 8000 - host: example.nl http: paths: - path: / pathType: Prefix backend: service: name: front-end port: number: 3000 - path: /api pathType: Prefix backend: service: name: back-end port: number: 8000
额外说明
你可以选择移除Ingress规则中host: example.nl的部分,因为所有example.nl的请求都会被重定向到www.example.nl,不会到达这部分规则配置的后端服务,能进一步简化配置。
内容的提问来源于stack exchange,提问作者Mathijs
相关产品推荐
相关产品推荐

