1. Optimize the Worker Infrastructure
NGINX is asynchronous and event-driven. You need to ensure it is utilizing your hardware properly.
- Worker Processes: Set
worker_processes auto;in yournginx.confto let NGINX automatically match the number of available CPU cores. - Worker Connections: Increase
worker_connectionsto2048or higher to handle more concurrent users per worker. - Multi-Accept: Enable
multi_accept on;to allow a worker to accept all new connections at once rather than one by one.
2. FastCGI Buffering and Timeouts
One of the most common “502 Bad Gateway” or slow-loading issues comes from NGINX being unable to handle the data coming back from PHP-FPM.
- Buffering: Enable
fastcgi_buffering on;. This allows NGINX to store the PHP response in memory so the PHP process can finish and move on to the next task immediately. - Buffer Sizes: Increase sizes to prevent NGINX from writing to disk (which is slow):Nginx
fastcgi_buffers 16 16k; fastcgi_buffer_size 32k;
3. Implement FastCGI Micro-caching
This is the “secret sauce” for high-traffic WordPress sites. Micro-caching caches dynamic PHP pages for a very short duration (e.g., 1 to 5 seconds).
- The Benefit: If 100 people hit your homepage at the same second, PHP only executes once; the other 99 users get the cached version from NGINX’s memory.
- The Config: Use
fastcgi_cache_pathin your HTTP block andfastcgi_cachewithin your server block to offload the application layer.
4. Directives for Static Assets
Stop letting PHP touch your static files. NGINX should handle images, CSS, and JS directly with aggressive cache headers.
- Browser Caching: Set
expires max;for static assets. - TCP Optimizations: Enable
sendfile on;andtcp_nopush on;. These directives allow NGINX to send files directly from the disk to the network buffer without copying them into the application memory first.
5. Gzip and Brotli Compression
Minimizing the payload size is critical for mobile performance.
- Brotli: If your NGINX build supports it, prioritize Brotli over Gzip. It provides better compression for text-based assets (HTML/CSS).
- Vary Header: Ensure
gzip_vary on;is set so that proxies don’t serve compressed content to browsers that don’t support it.