在 kubernetes GKE 上为 nginx 入口控制器设置缓存控制标头 [英] Setting cache-control headers for nginx ingress controller on kubernetes GKE
问题描述
我有一个 ingress-nginx 控制器处理到我托管在 GKE 上的 Kubernetes 集群的流量.我使用文档中的 helm 安装说明进行了设置:
I have an ingress-nginx controller handling traffic to my Kubernetes cluster hosted on GKE. I set it up using helm installation instructions from docs:
在大多数情况下,一切正常,但如果我尝试通过 server-snippet
注释设置缓存相关参数,则所有应获得缓存控制标头的服务内容都会作为一个 404
.
For the most part everything is working, but if I try to set cache related parameters via a server-snippet
annotation, all of the served content that should get the cache-control headers comes back as a 404
.
这是我的 ingress-service.yaml
文件:
apiVersion: extensions/v1beta1
kind: Ingress
metadata:
name: ingress-service
annotations:
kubernetes.io/ingress.class: nginx
nginx.ingress.kubernetes.io/proxy-read-timeout: "4000"
nginx.ingress.kubernetes.io/proxy-send-timeout: "4000"
nginx.ingress.kubernetes.io/server-snippet: |
location ~* .(js|css|gif|jpe?g|png)$ {
expires 1M;
add_header Cache-Control "public";
}
spec:
tls:
- hosts:
- example.com
secretName: example-com
rules:
- host: example.com
http:
paths:
- path: /
backend:
serviceName: client-cluster-ip-service
servicePort: 5000
- path: /api/
backend:
serviceName: server-cluster-ip-service
servicePort: 4000
同样,只有与正则表达式匹配的资源才会返回 404
(所有 .js
文件,.css
文件等).
Again, it's only the resources that are matched by the regex that come back as 404
(all .js
files, .css
files, etc.).
对为什么会发生这种情况有任何想法吗?
Any thoughts on why this would be happening?
感谢任何帮助!
推荐答案
那些 location
块是 最后和/或最长的比赛获胜,并且由于入口本身不提供任何此类内容,因此 nginx 依赖于 proxy_pass
指令 指向上游服务器.因此,如果您收到 404,很可能是因为 your location
匹配,从而干扰了 proxy_pass
一.你很有可能真的想要 configuration-snippet:
相反,可能与 if ($request_uri ~* ...) {
添加标题.
Those location
blocks are last and/or longest match wins, and since the ingress itself is not serving any such content, the nginx relies on a proxy_pass
directive pointing at the upstream server. Thus, if you are getting 404s, it's very likely because your location
is matching, thus interfering with the proxy_pass
one. There's a pretty good chance you'd actually want configuration-snippet:
instead, likely in combination with if ($request_uri ~* ...) {
to add the header.
您可以使用指向 python3 -m http.server 9090
或任何虚假上游目标的简单 nginx.conf 在本地尝试此操作.
One can try this locally with a trivial nginx.conf pointing at python3 -m http.server 9090
or whatever fake upstream target.
另外,为了调试 nginx 入口问题,查阅其实际的 nginx.conf
通常是非常宝贵的,它可以从任何一个入口 Pod 中获取,和/或查阅nginx 将在其中发出有用的调试文本的入口 Pod.
Separately, for debugging nginx ingress problems, it is often invaluable to consult its actual nginx.conf
, which one can grab from any one of the ingress Pods, and/or consulting the logs of the ingress Pods where nginx will emit helpful debugging text.
这篇关于在 kubernetes GKE 上为 nginx 入口控制器设置缓存控制标头的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!