k8s笔记16--ingress 配置 gzip 和 cache control

介绍

ngx_http_gzip_module模块是一个过滤器,它使用" gzip "方法来压缩响应,这常有助于将传输数据的大小减少一半甚至更多。在nginx 中需要通过 gzip on | off; 来开启或停止,在ingress 中欧你还需要在configmap 中 配置 use-gzip: true

Cache-Control HTTP报头字段保存请求和响应中的指令(指令),这些指令控制浏览器和共享缓存中的缓存, 开启该功能可以提利用本地的缓存文件,提高web访问效率。

案例

配置gzip

kube-system 配置 nginx-configuration
新增 use-gzip: true

ingress 的 中新增:
annotations:
  nginx.ingress.kubernetes.io/server-snippet: gzip on;

以下为阿里云 ingress 的configmap默认配置:

apiVersion: v1
data:
  allow-backend-server-header: 'true'
  enable-underscores-in-headers: 'true'
  generate-request-id: 'true'
  ignore-invalid-headers: 'true'
  log-format-upstream: >-
    $remote_addr - [$remote_addr] - $remote_user [$time_local] "$request"
    $status $body_bytes_sent "$http_referer" "$http_user_agent" $request_length
    $request_time [$proxy_upstream_name] $upstream_addr
    $upstream_response_length $upstream_response_time $upstream_status $req_id
    $host [$proxy_alternative_upstream_name]
  max-worker-connections: '65536'
  proxy-body-size: 4096m
  proxy-connect-timeout: '10'
  reuse-port: 'true'
  server-tokens: 'false'
  ssl-redirect: 'false'
  upstream-keepalive-timeout: '900'
  use-gzip: 'true'
  worker-cpu-affinity: auto
kind: ConfigMap
metadata:
  labels:
    app: ingress-nginx
  name: nginx-configuration
  namespace: kube-system

在这里插入图片描述
配置cache control

ingress 的 中新增如下内容,可以通过request_uri按需配置指定文件的cache control:
  annotations:
    nginx.ingress.kubernetes.io/configuration-snippet: >
      more_set_headers "cache-Control: no-cache, no-store"; if ($request_uri ~*
      \.(?:ico|css|js|gif|jpe?g|png|svg|woff2|woff|ttf|eo|mp3|glb)$) {
        more_set_headers "cache-control: public, max-age=2592000";
      }

最终输出效果:
Content-Encoding: gzip
Cache-Control: public, max-age=2592000在这里插入图片描述

注意事项

  1. 配置cache control需要在 configuration-snippet 中配置, 若在 server-snippet 中配置则无法过滤指定的文件格式。
  2. 配置gzip的时候,若更改好ingress controler 的configmap, 默认情况下所有域名都开了gzip,若需要关闭指定的域名,那么直接在 annotations 中设置 nginx.ingress.kubernetes.io/server-snippet: gzip off;

说明

NGINX Ingress Controller/ConfigMaps
What is the best nginx compression gzip level
简单聊聊 GZIP 的压缩原理与日常应用
developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Cache-Control

Logo

为开发者提供学习成长、分享交流、生态实践、资源工具等服务,帮助开发者快速成长。

更多推荐