From 8d6f4616b9092d6119eae8a44316f51b666aab6d Mon Sep 17 00:00:00 2001 From: yuetsh <517252939@qq.com> Date: Wed, 5 Aug 2026 09:11:48 -0600 Subject: [PATCH] =?UTF-8?q?perf(nginx):=20=E4=BF=AE=E5=A4=8D=20JS=20?= =?UTF-8?q?=E6=9C=AA=E5=8E=8B=E7=BC=A9=EF=BC=8C=E9=9D=99=E6=80=81=E8=B5=84?= =?UTF-8?q?=E6=BA=90=E5=8A=A0=E4=B8=8D=E5=8F=AF=E5=8F=98=E7=BC=93=E5=AD=98?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit nginx 1.21.1 起 mime.types 把 .js 标成 text/javascript,而 gzip_types 只写了 application/javascript,导致前端 JS 实际一直在裸传。补全类型列表, 并加上 application/json 让 API 响应也走压缩。 gzip_comp_level 此前用的是默认值 1,改为 6,实测 js+css 总量 3.85M → 3.44M。 /assets/ 下的产物文件名带内容 hash,加 immutable 永久缓存,省掉每次进页面 对 32 个 chunk 的条件请求;index.html 反过来设 no-cache,避免发版后刷不到新版。 location 里出现 add_header 会中断 http 级 add_header 的继承, 两个 block 都重新声明了原有的三个安全头。 Co-Authored-By: Claude Opus 5 --- deploy/nginx/locations.conf | 21 +++++++++++++++++++++ deploy/nginx/nginx.conf | 13 ++++++++++++- 2 files changed, 33 insertions(+), 1 deletion(-) diff --git a/deploy/nginx/locations.conf b/deploy/nginx/locations.conf index a9a9139..17d0018 100644 --- a/deploy/nginx/locations.conf +++ b/deploy/nginx/locations.conf @@ -32,7 +32,28 @@ location /.well-known { alias /data/ssl/.well-known; } +# 注意:location 里一旦出现 add_header,http 级的 add_header 就不再继承, +# 所以下面两个 block 都要把 nginx.conf 里的安全头重新写一遍。 + +# 构建产物文件名带内容 hash,内容一变文件名就变,可以永久缓存。 +# 命中后浏览器直接读磁盘,不再发条件请求。 +location /assets/ { + root /app/dist; + expires 1y; + add_header Cache-Control "public, immutable"; + add_header X-XSS-Protection "1; mode=block" always; + add_header X-Frame-Options SAMEORIGIN always; + add_header X-Content-Type-Options nosniff always; + access_log off; +} + location / { root /app/dist; try_files $uri $uri/ /index.html =404; + # index.html 引用着带 hash 的文件名,必须每次回源校验, + # 否则发新版后学生刷不到。no-cache 是"缓存但每次校验",命中走 304。 + add_header Cache-Control "no-cache"; + add_header X-XSS-Protection "1; mode=block" always; + add_header X-Frame-Options SAMEORIGIN always; + add_header X-Content-Type-Options nosniff always; } diff --git a/deploy/nginx/nginx.conf b/deploy/nginx/nginx.conf index 4beafdc..839a585 100644 --- a/deploy/nginx/nginx.conf +++ b/deploy/nginx/nginx.conf @@ -19,7 +19,18 @@ http { gzip on; gzip_vary on; - gzip_types application/javascript text/css; + gzip_comp_level 6; + gzip_min_length 1024; + # nginx 1.21.1 起 mime.types 把 .js 标成 text/javascript, + # 只写 application/javascript 会导致前端 JS 完全不压缩,两个都要留。 + # text/html 是内置的,不用也不能写在这里。 + gzip_types + text/javascript + application/javascript + text/css + application/json + image/svg+xml + text/plain; log_format main '$remote_addr - $remote_user [$time_local] "$request" ' '$status $body_bytes_sent "$http_referer" '