webzod
account

Make the largest element on the page load faster on nginx

perf.cwv.lcp_needs_improvement · effort: about an hour

Why it matters

Largest Contentful Paint is how long visitors wait before the main image or heading shows, and the value is above the good threshold. A few changes to the main image and caching usually bring it into the good range.

Staged change. Do this in stages and check each one before the next, so a mistake does not break your site or your mail.

The fix

  1. Turn on compression for text files and give files whose names change with their content a long cache lifetime, so repeat visits and the CDN do not fetch them again. Only use the long lifetime for fingerprinted files (such as app.3f9c2a.js); for others change 1y to a shorter time such as 1h.
  2. Put the lines inside the server block for example.com and repeat what your location / uses to serve files. The snippet serves files from the server's root with try_files; if location / proxies to an application, put the same proxy_pass line in the new location instead of try_files.
  3. Run nginx -t and reload nginx. If nginx -t reports a duplicate gzip or gzip_vary directive, change the existing one instead of adding a second. Check the Cache-Control and Content-Encoding headers with curl -I --compressed on a css or js file.
/etc/nginx/conf.d/example.com.conf
gzip on;
gzip_vary on;
gzip_types text/css application/javascript text/javascript application/json image/svg+xml;

location ~* \.(?:css|js|woff2|avif|webp|png|jpe?g|svg)$ {
    expires 1y;
    try_files $uri =404;   # use the same root or proxy_pass as your location / block
}

The examples use example.com. Replace it with your own domain.

Read the documentation (opens in a new tab)

Scan your domain to see whether this applies to you.