Improve PageSpeed Score with Nginx
Nginx can improve the server-side parts of a PageSpeed Insights result by compressing text, caching static files, and avoiding slow redirects or responses. These changes cannot fix oversized images, render-blocking scripts, or poor front-end code by themselves, so measure before and after and address the specific bottlenecks reported.
What You’ll Need
- Administrative access to the server and permission to edit its Nginx configuration.
- A backup of the current configuration and a way to restore it.
- A terminal, the Nginx configuration test command, and a PageSpeed measurement of the affected page.
- HTTPS already configured if the page is served securely. Test representative pages, including dynamic pages and static assets.
Step-by-Step
- Record a baseline. Run PageSpeed Insights on the exact URL, and note both mobile and desktop results. Review the diagnostics and Core Web Vitals, especially Largest Contentful Paint (LCP), Interaction to Next Paint (INP), and Cumulative Layout Shift (CLS). Also inspect response headers and timing with your browser’s developer tools or a command-line HTTP client. Save the results; a single score can vary between runs.
- Find the active configuration. Check how Nginx is installed and which configuration files it loads. Common locations include
/etc/nginx/nginx.confand files included from directories such as/etc/nginx/conf.d/or/etc/nginx/sites-enabled/, but installations differ. Usenginx -Tto print the effective configuration, taking care not to publish output that contains sensitive information. Back up the files you plan to edit. - Enable gzip for text responses. In the Nginx
httpcontext, enable gzip and choose types that are actually served by the site. For example:gzip on;
gzip_vary on;
gzip_min_length 1024;
gzip_comp_level 5;
gzip_types text/plain text/css application/javascript application/json application/xml image/svg+xml;
Nginx compresses eligible responses when the client advertises support. Do not add already-compressed formats such as JPEG, WebP, PNG, ZIP, or most font files. Avoid setting a high compression level without testing CPU use; the default can be a sensible starting point. Confirm the response hasContent-Encoding: gzipand that its content type is eligible. - Consider Brotli only if it is available. Brotli can reduce some text payloads, but it is not built into every Nginx installation. Check the installed build and modules before adding directives such as
brotli on;; an unknown directive will prevent Nginx from loading the configuration. If a supported module is available, configure it for text types and use gzip as a fallback where appropriate. Verify the negotiated encoding in response headers rather than assuming it is active. - Set browser caching for versioned static assets. For files whose names change whenever their contents change, such as
app.a1b2c3.js, a long-lived cache policy can avoid repeat downloads. Place a location rule in the correct server context, adapting the file types and path to your site:location ~* \.(css|js|png|jpg|jpeg|gif|svg|webp|woff2)$ {
expires 1y;
add_header Cache-Control "public, max-age=31536000, immutable";
}
Do not apply a year-long immutable policy to assets that keep the same URL when their contents change. For unversioned files, use a shorter lifetime or revalidation policy. Be especially cautious with HTML and personalized responses: caching them publicly can show stale or private content. - Check redirects and TLS setup. Link directly to the final HTTPS URL and avoid chains such as HTTP to a hostname variant and then to HTTPS. Keep redirects only where needed. Reuse an established, secure TLS configuration rather than copying outdated cipher settings from a random snippet. If HTTP/2 is supported by your Nginx and TLS setup, enable it using the syntax supported by that installation and verify the negotiated protocol in the browser. Protocol changes alone do not guarantee a higher score.
- Test before applying changes. Run
sudo nginx -t(or the equivalent command for your installation). If the test reports an error, correct it before reloading. Once the test passes, reload gracefully withsudo systemctl reload nginxwhere systemd is used; service names and reload commands can vary. Check the service status and error log immediately after reloading. - Verify behavior and measure again. Request a page and several asset types with a fresh browser session. Confirm the status codes, redirects, compression headers, cache headers, and that dynamic or private pages are not being cached incorrectly. Purge any relevant proxy or CDN cache, then run PageSpeed Insights again under comparable conditions. Compare the detailed diagnostics and field data over time, not just one lab score.
- Improve what Nginx cannot fix. If LCP is still poor, inspect the largest visible image, server response time, and render-blocking resources. Resize and compress images, serve modern formats where suitable, defer noncritical JavaScript, reduce unused CSS, and reserve space for images or embeds to prevent layout shifts. These changes usually belong in the application or its build pipeline, not an Nginx directive.
Common Mistakes
- Putting a directive in the wrong context. For example,
gzipsettings belong in thehttp,server, or supported location context; check the Nginx documentation for each directive. - Applying long-lived caching to HTML, user-specific responses, or assets without versioned filenames. Visitors may keep seeing outdated content.
- Trying to compress images or other formats that are already compressed, increasing CPU work without meaningful savings.
- Copying Brotli, HTTP/2, or TLS directives without checking the installed Nginx version, modules, and configuration syntax.
- Judging success from one PageSpeed run. Network conditions, device emulation, cache state, and third-party services can change lab results.
Tips
- Make one change at a time and keep a note of the affected file, expected behavior, and result. That makes regressions easier to isolate.
- Use content-hashed filenames for static assets before setting an immutable cache policy. When a file changes, its URL should change too.
- Check both compressed and uncompressed responses, and ensure caches vary correctly by the
Accept-Encodingrequest header.gzip_vary on;helps signal this for gzip responses. - If a CDN or reverse proxy sits in front of Nginx, identify which layer sets compression and cache headers. Conflicting policies can cancel out or cause stale content.
- Prioritize user experience and field Core Web Vitals over chasing a perfect lab score. A score is a diagnostic summary, not a direct measure of every visitor’s experience.
Troubleshooting
Nginx refuses to reload: Run nginx -t and read the reported file and line. Look for a missing semicolon, unmatched brace, misspelled directive, or directive placed in an unsupported context. Restore the backup if needed, test again, and reload only after validation succeeds.
Compression is missing: Check that the response is large enough, uses a configured text content type, and that the request accepts the encoding. Inspect any CDN or proxy in front of Nginx, since it may compress the response itself or alter headers. Do not judge compression from a cached response alone.
Changes are not reflected in the browser: Clear browser and intermediary caches, verify the request reaches the intended Nginx server block, and inspect the actual response headers. Check whether the application or CDN overrides Cache-Control or redirects the URL.
The score is unchanged or worse: Compare the specific audit that failed. If the problem is image size, JavaScript execution, third-party scripts, or layout shifts, server configuration may not affect it. Revert any change that raises server load or breaks content, then address the diagnosed front-end issue.
Frequently Asked Questions
Can Nginx guarantee a 100 PageSpeed score?
No. Nginx can improve delivery and caching, but the score also depends on page design, assets, scripts, hosting, and test conditions.
Should I enable gzip and Brotli together?
They can be configured as supported alternatives, but the server should send an encoding the client accepts. Confirm the installed module and verify the response headers.
Is a one-year cache safe for every file?
No. Use it only for assets with URLs that change when their contents change. Use short caching or revalidation for unversioned files and dynamic content.
Will HTTP/2 automatically improve my score?
Not necessarily. It can improve connection handling in some situations, but it does not replace image optimization, efficient code, or good server response times.
How often should I rerun PageSpeed Insights?
Run it after meaningful changes, using the same URL and comparable conditions. For real-user performance, review field data over a longer period as it becomes available.
Related
Method: the standard formula for this calculation, rounded as each result states. See how the calculators work or report an error.