nginx 캐시 된 index.html 강제 다시로드

Dec 12 2020

서버 마이그레이션 중에 새로운 nginx 구성에 캐시 제어 지시문이 누락되었습니다. 따라서 우리는 index.html새 코드를 배포하면 더 이상 새로 고쳐지지 않는 SPA에 매우 나쁜 캐시로 끝났습니다 . 캐시되지 않도록 index.html이 필요합니다.

이것은 언젠가 온라인 상태였던 (나쁜) nginx 구성이었습니다.

server {
  listen 80;

  location / {
    root   /usr/share/nginx/html;
    index  index.html index.htm;
    try_files $uri $uri/ /index.html;
  }

  error_page   500 502 503 504  /50x.html;

  location = /50x.html {
    root   /usr/share/nginx/html;
  }

}

구성을 수정했습니다.

server {
  listen 80;

  root /usr/share/nginx/html;

  location / {
    index  index.html index.htm;
    try_files $uri $uri/ /index.html;
    add_header Cache-Control "no-store, no-cache, must-revalidate";
  }

  location ~* \.(js|jpg|jpeg|gif|png|svg|css)$ {
    add_header Cache-Control "max-age=31536000, public";
  }

  error_page   500 502 503 504  /50x.html;

  location = /50x.html {
    root   /usr/share/nginx/html;
  }

}

질문

지난 며칠 동안 웹 페이지를 방문한 클라이언트는 이전 index.html을 캐시했습니다. 브라우저가 캐시를 삭제하도록 강제 할 수있는 방법은 index.html무엇입니까?

답변

1 Talkerbox Dec 17 2020 at 16:38

클라이언트가 서버에 새 콘텐츠를 요청하지 않는 동안에는 사용자 측 (브라우저)에서 브라우저 캐시를 수동으로 재설정 할 수 없습니다. 이 경우 SPA가 캐시없이 다운로드되는 모든 스크립트에 대한 유용한 액세스가 될 수 있습니다. 이 경우이 스크립트를 변경하고 강제 재로드 페이지를 실행할 수 있습니다 (그러나주의하십시오-모든 페이지로드 후에 영구적 인 강제 재로드를 방지하기위한 플래그가 필요합니다). 예를 들어 사이트에 GTM이있는 경우 도움이 될 수 있습니다.

UPD : 저는 js 전문가는 아니지만 다음 js-script와 같은 모든 페이지에 GTM 태그를 추가해야합니다.

function getCookie(name) {
  let matches = document.cookie.match(new RegExp(
    "(?:^|; )" + name.replace(/([\.$?*|{}\(\)\[\]\\\/\+^])/g, '\\$1') + "=([^;]*)"
  ));
  return matches ? decodeURIComponent(matches[1]) : undefined;
}

was_reloaded = getCookie('was_reloaded')
alert(was_reloaded)
if (was_reloaded != 'yes') {
        document.cookie = "was_reloaded=yes; path=/; max-age=3600;"
    location.reload();
} }