Make the largest element on the page load faster on nginx
Why it matters
Largest Contentful Paint is how long visitors wait before the main image or heading shows, and a poor value means many of them wait too long. Google counts this in its page experience signals and slow pages lose visitors.
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
- 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.
- 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.
- 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.
Related
- Reported by the Core Web Vitals check
- Make the largest element on the page load faster
- Stop the page layout from jumping while it loads
- Stop the page layout from jumping while it loads
- Make the page respond faster to clicks and taps
- Make the page respond faster to clicks and taps
- Reduce the JavaScript that blocks the page while it loads
- Reduce the JavaScript that blocks the page while it loads
- Collect real-user speed data for your site
Scan your domain to see whether this applies to you.