متقدم
البحث فيأدلة «كيف»
طريقة البحث
  • اكتب المهمة بكلماتك (find port، open firewall، disk full) أو الصق رسالة الخطأ بين علامتي تنصيص.
  • اختر «الإجابة السريعة» لترى الأوامر فقط، أو مجالًا لتبقى في مجال واحد.
  • "كلمتان" تجد العبارة بالضبط.
  • الكلمات العادية تجد الأسماء والنصوص والأمثلة.
  • ↑ ↓ للتنقل · Enter للفتح · Esc للإغلاق · / للبحث
جرّب:

كيف 196Web · Nginx

How to cache static files in Nginx

Every page view loads the same CSS, JavaScript, fonts and images again — slow for visitors and needless work for the server. With the right Cache-Control headers the browser keeps these files for a year and asks for them never again; with gzip they travel smaller; and with proxy_cache Nginx can even keep copies of slow backend responses. This how-to sets safe cache rules that never serve an old version after a deploy.

  • 5 الدروس
  • 5 الأوامر

هذا الجزء لم يُترجم بعد. أنت ترى النص الإنجليزي.

$ مستخدم عادي# بصلاحية root (أو مع sudo)

196.1

The quick answer

server block
location ~* \.(?:css|js|woff2|png|jpg|jpeg|webp|avif|svg|ico)$ {
    add_header Cache-Control "public, max-age=31536000, immutable" always;
    access_log off;
    try_files $uri =404;
}
 
location / {
    add_header Cache-Control "no-cache" always;
    try_files $uri $uri/ /index.html;
}
 
gzip on;
gzip_comp_level 5;
gzip_min_length 1024;
gzip_types text/css application/javascript application/json image/svg+xml;
nginx -t && systemctl reload nginx
curl -sI https://www.example.com/assets/app.3f9a1c.css | grep -i cache-control

196.2

Step by step

  1. Long cache only for versioned files — immutable for one year is safe only when the file name changes with its content (app.3f9a1c.css), which build tools (Vite, webpack) do. For files without a hash use a short max-age (for example 1 hour).
  2. HTML is never cached long — no-cache means "ask the server each time" (cheap with ETag/Last-Modified, Nginx sends them for files). So a new deploy is visible at once and points to the new asset names.
  3. Compress text — gzip for CSS, JS, JSON, SVG (HTML is always included). Do not gzip images or fonts that are already compressed (PNG, JPG, WebP, WOFF2).
  4. Pre-compressed files — if the build creates .gz files, gzip_static on; serves them without CPU work.
  5. Cache a slow backend — for API answers that are the same for everybody:
http + location
proxy_cache_path /var/cache/nginx/app levels=1:2 keys_zone=app:50m max_size=1g inactive=60m use_temp_path=off;
 
location /api/catalog/ {
    proxy_cache app;
    proxy_cache_valid 200 10m;
    proxy_cache_use_stale error timeout updating;
    add_header X-Cache-Status $upstream_cache_status always;
    proxy_pass http://127.0.0.1:8080;
}

Never cache answers with personal data or Set-Cookie.

  1. Watch the inheritance — add_header in these locations replaces the server-level headers; include your security header snippet there too.
  2. CDN — a CDN in front respects the same Cache-Control headers; purge it after deploys of non-versioned files.

الأوامر في هذا الدرس

196.3

Check that it worked

The asset shows Cache-Control: public, max-age=31536000, immutable; the HTML shows no-cache; curl -sI -H 'Accept-Encoding: gzip' …/app.3f9a1c.css shows Content-Encoding: gzip; for the API, the second request shows X-Cache-Status: HIT. In the browser's network tab, reloads show assets "from memory/disk cache".

الأوامر في هذا الدرس

196.4

Common problems

ProblemCauseFix
Users see the old site after a deployHTML or unversioned files cached long.no-cache for HTML; long cache only for hashed names.
Two Cache-Control headersexpires and add_header Cache-Control both used.Use one of them (only add_header here).
Security headers missing on assetsadd_header in the location stops inheritance.Include the security snippet in the location.
No Content-Encoding: gzipType not in gzip_types (or no include mime.types, so CSS is text/plain), file smaller than gzip_min_length, or no Accept-Encoding.Add the type; keep include mime.types;; test with the header.
X-Cache-Status always MISSBackend sends Set-Cookie or Cache-Control: private.Fix the backend headers, or proxy_ignore_headers only for public data.
Cache folder fills the diskNo max_size.Set max_size and inactive.

196.5

Go further

1When is a one-year immutable cache safe?

Only for files whose name changes with their content (a hash in the name), so a new version always has a new URL.

2Why should HTML use no-cache?

The browser checks with the server every time, so after a deploy it gets the new page that points to the new files.

الأوامر في هذا الدرس

كل الأوامر في هذا الفصل