通过 nginx 替换指纹文件服务器时使浏览器中的资产缓存过期
Expire assets cache in browsers when replacing fingerprinted files server via nginx
我正在通过 nginx 为单个页面 JavaScript 应用程序提供服务,当我部署新版本时,我想强制浏览器使它们的 JS 缓存失效,并 request/use 最新版本可用。
因此,例如,当我将服务器文件夹中名为 my-app-8e8faf9.js
的文件替换为名为 my-app-eaea342.js
的文件时,我不希望浏览器从它们的文件中提取 my-app-8e8faf9.js
缓存了。但是当没有可用的新版本时,我仍然希望他们从缓存中读取资产。
如何使用 nginx 配置实现此目的?这是我现有的配置:
server {
listen 80;
server_name my.server.com;
root /u/apps/my_client_production/current;
index index.html;
# ~2 seconds is often enough for most folks to parse HTML/CSS and
# retrieve needed images/icons/frames, connections are cheap in
# nginx so increasing this is generally safe...
keepalive_timeout 10;
client_max_body_size 100M;
access_log /u/apps/my_client_production/shared/log/nginx.access.log;
error_log /u/apps/my_client_production/shared/log/nginx.error.log info;
location / {
try_files $uri $uri/ =404;
gzip_static on;
expires max;
add_header Cache-Control public;
}
# Error pages
error_page 500 502 503 504 /500.html;
}
通过更改资产 url 使缓存失效是一种正常做法。
但要实现这一点,您需要 html 文件不要永远缓存,这样当这些名称更改时浏览器就会有一些信息。
因此 html 和资产的位置分开。匹配器可以不同,这取决于你如何存储它们,例如:
location / {
try_files $uri $uri/ =404;
gzip_static on;
}
location ^~ /assets/ {
gzip_static on;
expires max;
add_header Cache-Control public;
}
我正在通过 nginx 为单个页面 JavaScript 应用程序提供服务,当我部署新版本时,我想强制浏览器使它们的 JS 缓存失效,并 request/use 最新版本可用。
因此,例如,当我将服务器文件夹中名为 my-app-8e8faf9.js
的文件替换为名为 my-app-eaea342.js
的文件时,我不希望浏览器从它们的文件中提取 my-app-8e8faf9.js
缓存了。但是当没有可用的新版本时,我仍然希望他们从缓存中读取资产。
如何使用 nginx 配置实现此目的?这是我现有的配置:
server {
listen 80;
server_name my.server.com;
root /u/apps/my_client_production/current;
index index.html;
# ~2 seconds is often enough for most folks to parse HTML/CSS and
# retrieve needed images/icons/frames, connections are cheap in
# nginx so increasing this is generally safe...
keepalive_timeout 10;
client_max_body_size 100M;
access_log /u/apps/my_client_production/shared/log/nginx.access.log;
error_log /u/apps/my_client_production/shared/log/nginx.error.log info;
location / {
try_files $uri $uri/ =404;
gzip_static on;
expires max;
add_header Cache-Control public;
}
# Error pages
error_page 500 502 503 504 /500.html;
}
通过更改资产 url 使缓存失效是一种正常做法。
但要实现这一点,您需要 html 文件不要永远缓存,这样当这些名称更改时浏览器就会有一些信息。
因此 html 和资产的位置分开。匹配器可以不同,这取决于你如何存储它们,例如:
location / {
try_files $uri $uri/ =404;
gzip_static on;
}
location ^~ /assets/ {
gzip_static on;
expires max;
add_header Cache-Control public;
}