Nginx 不立即缓存页面

Nginx 不立即缓存页面

我正在使用 Nginx 的 proxy_cache 模块进行缓存,但注意到页面不会立即缓存。内容非常动态,每次页面加载都会产生不同的布局,我试图将布局缓存一个小时。

Nginx 似乎只有在多次请求后才会缓存页面迅速地。这是我的配置。

proxy_cache_path  /var/cache/nginx levels=1:2 keys_zone=one:8m max_size=1000m; #caching
proxy_temp_path /var/tmp; #caching

proxy_cache_valid 404 500 1m;
proxy_cache_valid 200 60m;
proxy_cache_min_uses 1;

gzip_comp_level 6;
gzip_vary on;
gzip_min_length  1000;
gzip_proxied any;
gzip_types text/plain text/css application/json application/x-javascript text/xml application/xml application/xml+rss text/javascript;
gzip_buffers 16 8k;

upstream staging {
  server 127.0.0.1:1337;
  server 127.0.0.1:7331;
}

server {
  listen 0.0.0.0:80;
  server_name dev.example.com;
  access_log /var/log/nginx/dev.example.log;
  error_log  /var/log/nginx/dev.example.error.log debug;   log_subrequest on;

  location ~ ^/(images/|scripts/|styles/|robots.txt|humans.txt|favicon.ico) { #caching
    root /home/example/app/website/public;
    access_log off;
    expires max;
  }

  location /ssi { #Our serverside includes
    proxy_pass http://staging;
  }

  location / {
    ssi on;

    #auth_basic "Restricted";
    #auth_basic_user_file /etc/nginx/.htpasswd;

    proxy_redirect off;
    proxy_set_header X-Real-IP $remote_addr;
    proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
    proxy_set_header Host $http_host;
    proxy_set_header X-NginX-Proxy true;

    proxy_cache one; #caching
    proxy_cache_key sfs$request_uri$scheme; #caching

    proxy_http_version 1.1;
    proxy_pass http://staging/; #points to the upstream staging
  }
}

server {
  listen 0.0.0.0:80;
  server_name static.example.com;

  location ~ ^/(images/|scripts/|styles/|robots.txt|humans.txt|favicon.ico) { #caching
    add_header Access-Control-Allow-Origin *.example.com;
    root /home/example/app/website/public;
    access_log off;
    expires max;
  }

  location / {
    return 404;
  }

}

答案1

nginx 根据某些标头决定是否可以缓存上游响应。从文档

以下响应标头将响应标记为不可缓存,除非它们被忽略:

  • 设置Cookie
  • Cache-Control 包含“no-cache”、“no-store”、“private”或“max-age”,且值为非数字或 0
  • 过期时间为过去的某个时间
  • X-Accel-Expires:0

检查上游发送给 nginx 的标头并确保它们允许缓存。

相关内容