我无法让 NGINX 根据 MIME 类型正确发送缓存控制标头。它适用于某些类型,但对其他类型无效。我遗漏了什么?
在我的site.conf
档案中我有:
map $sent_http_content_type $expires {
default off;
text/html epoch;
text/css 1h;
text/javascript 1h;
application/javascript 1h;
# ~image/ 1h;
image/webp 1h;
image/png 2h;
~font/ 1h;
}
server {
server_name ...;
...
root /var/www/site;
index index.html;
expires $expires;
location / {
proxy_pass http://127.0.0.1:5001;
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection 'upgrade';
proxy_set_header Host $host;
proxy_cache_bypass $http_upgrade;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
}
...
}
使用图像效果很好。它也可以与~image/
图案配合使用。
curl -I https://site.tld/images/image.webp
HTTP/2 200
server: nginx/1.18.0 (Ubuntu)
date: Thu, 22 Sep 2022 14:37:16 GMT
content-type: image/webp
content-length: 9488
accept-ranges: bytes
expires: Thu, 22 Sep 2022 15:37:16 GMT
cache-control: max-age=3600
strict-transport-security: max-age=2628000; includeSubDomains
$ curl -I https://site.tld/images/image.png
HTTP/2 200
server: nginx/1.18.0 (Ubuntu)
date: Thu, 22 Sep 2022 14:37:25 GMT
content-type: image/png
content-length: 53676
accept-ranges: bytes
expires: Thu, 22 Sep 2022 16:37:25 GMT
cache-control: max-age=7200
strict-transport-security: max-age=2628000; includeSubDomains
但它拒绝与 CSS 或 javascript 一起工作......
$ curl -I https://site.tld/css/bootstrap.min.css
HTTP/2 200
server: nginx/1.18.0 (Ubuntu)
date: Thu, 22 Sep 2022 14:43:39 GMT
content-type: text/css; charset=utf-8
content-length: 162264
vary: Accept-Encoding
accept-ranges: bytes
strict-transport-security: max-age=2628000; includeSubDomains
$ curl -I https://site.tld/js/bootstrap.min.js
HTTP/2 200
server: nginx/1.18.0 (Ubuntu)
date: Thu, 22 Sep 2022 14:43:53 GMT
content-type: text/javascript; charset=utf-8
content-length: 62563
vary: Accept-Encoding
accept-ranges: bytes
strict-transport-security: max-age=2628000; includeSubDomains
该应用程序是一个已编译的 Go 应用,其中的图像资源已编译并通过代理提供。但所有资源都已编译,包括图像和 CSS 等。那么为什么它对某些类型有效,而对其他类型无效呢?
答案1
您尝试设置缓存的内容类型具有字符集。这也应该是规则的一部分:
map $sent_http_content_type $expires {
default off;
text/html epoch;
text/css 1h;
text/javascript 1h;
application/javascript 1h;
# ~image/ 1h;
image/webp 1h;
image/png 2h;
~font/ 1h;
"text/ccs; charset=utf-8" 1h;
"text/javascript; charset=utf-8" 1h;
}
否则将属于default
设置范围。