Skip to content

Instantly share code, notes, and snippets.

@popstas
Created September 30, 2022 11:06
Show Gist options
  • Save popstas/be07c5ce0490416288cc31cd08f8acdc to your computer and use it in GitHub Desktop.
Save popstas/be07c5ce0490416288cc31cd08f8acdc to your computer and use it in GitHub Desktop.

Кеширование страницы на nginx на минуту

В nginx.conf:

proxy_cache_path /var/cache/nginx keys_zone=cache_pages:16m max_size=10g;

Создать /etc/nginx/snippets/proxy_cache_force.conf:

# https://www.nginx.com/blog/nginx-caching-guide/
proxy_cache cache_pages;
proxy_cache_valid 200 1m;
proxy_cache_min_uses 1;
proxy_read_timeout 20s;
proxy_cache_use_stale error timeout updating http_500 http_502 http_503 http_504;
proxy_cache_background_update on;
proxy_cache_lock on;
proxy_ignore_headers Cache-Control;
default_type text/html;
#add_header Content-type "text/html; charset=utf-8";

В главный location сайта, рядом с нужным proxy_pass:

include snippets/proxy_cache_force.conf;

Чтобы сделать неубиваемой главку, надо для неё сделать отдельный location в секции server:

location = / {
  proxy_cache_key $scheme$http_host$uri; # Осторожно! Тут кеширование без учёта get параметров, т.к. долбят главку рандомными get
  include snippets/proxy_cache_force.conf;

  # отсюда идёт проксирование на бэк
  add_header Cache-Control public;
  proxy_pass http://localhost:8080; # 
  proxy_set_header  X-Real-IP  $remote_addr;
  proxy_set_header  X-Forwarded-For $proxy_add_x_forwarded_for;
  proxy_set_header  X-Forwarded-Proto $scheme;
  proxy_set_header  X-Forwarded-Host  $http_host;
  proxy_set_header  X-Forwarded-Port  $server_port;
  proxy_set_header  Host $http_host;
  proxy_redirect    off;
  proxy_next_upstream error timeout invalid_header http_502;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment