Configure Nginx FastCGI Cache To Speed ​​Up WordPress Server Response Time - LinuxBabe (2023)

This tutorial will show you how to configure Nginx FastCGI caching to reduce server response time for your WordPress website.

What is Nginx FastCGI cache?

If you followed my previous tutorialsLEMP Stack InstallationOn many Linux distributions, Nginx is configured to forward the PHP request to PHP-FPM because Nginx itself cannot process PHP code. Let me explain how a LEMP stack site works.

  1. Web browsers send HTTP requests to Nginx, which tries to get the page from the file system.
  2. When Nginx finds PHP codes in the page, it forwards the request to PHP-FPM to process the PHP codes.
  3. When necessary, PHP-FPM will query the MySQL/MariaDB database to get what is needed.
  4. PHP-FPM generates a static HTML page, which is then returned to Nginx.
  5. Finally, Nginx sends the static HTML page to the web browser.

Nginx is super fast when it comes to serving static HTML pages. However, PHP is notoriously slow despite the latest version.PHP8it is much faster than previous versions. And the MySQL/MariaDB database is anotherPerformance Bottleneck of LEMP Stack Sites.

Instead of passing the dynamic page request to PHP-FPM and letting it generate the HTML page each time, Nginx can cache the generated HTML page so that the next time the cached pages are sent it can be sent to the hosts. web browsers, eliminating PHP and database requests.

  • This can greatly improve server response time and reduce the load on PHP-FPM and the database server.
  • It also allows Nginx to serve web pages from the cache when the upstream PHP-FPM or database server is down (MySQL/MariaDB is usually the first process killed when the Linux server runs out of memory).

FastCGI is the protocol between Nginx and PHP-FPM, so the cache is called FastCGI cache.

How to configure Nginx FastCGI caching

Step 1 – Edit the main Nginx configuration file

Edit the main Nginx configuration file.

sudo nano /etc/nginx/nginx.conf

NOhttp {…}context, add the following 2 lines:

fastcgi_cache_path /usr/share/nginx/fastcgi_cache level=1:2 keys_zone=phpcache:100m max_size=10g inactive=60m use_temp_path=off;fastcgi_cache_key "$scheme$request_method$host$request_uri";

Configure Nginx FastCGI Cache To Speed ​​Up WordPress Server Response Time - LinuxBabe (1)

the first directivefastcgi_cache_pathcreates a FastCGI cache. This policy is only available on thehttpContext of an Nginx configuration file.

  • The first argument specifies the location of the cache on the file system (/usr/share/nginx/fastcgi_cache/).
  • olevelsThe parameter configures a two-level directory hierarchy under/usr/share/nginx/fastcig_cache/. A large number of files in a single directory can slow down file access, so I recommend a two-level directory for most deployments. If helevelsThe parameter is not included, Nginx puts all the files in the same directory. The first directory uses a character in its name. The subdirectory uses two characters in its name.
  • The third argument specifies the name of the shared memory zone (phpcache) and its size (100 MB). This storage zone is used to store cache keys and metadata, such as usage times. By keeping a copy of the keys in memory, Nginx can quickly determine if a request is HIT or MISS without going to disk, making verification much faster. A 1 MB zone can store data for about 8,000 keys, so a 100 MB zone can store data for about 800,000 keys.
  • maximum sizesets the upper limit of the cache size (10 GB in this example). If not specified, the cache can use all the remaining space. When the cache reaches its maximum size, the Nginx cache manager removes the most frequently used files from the cache.
  • The cache manager removes data that has not been accessed during the idle time (60 minutes), regardless of whether it has expired or not. The default is 10 minutes. You can also use values ​​like12h(12 hours) and7d(7 diameters).
  • Nginx first writes the files destined for the cache to a temporary storage area (/var/lib/nginx/fastcgi/).use_temp_path=austells Nginx to write them directly to the final cache directory to avoid unnecessary copying of data between file systems.

the second directivefastcgi_cache_keysets the key for the cache lookup. Nginx applies an MD5sum hash function to the cache key and uses the hash result as the names of the cache files. After inserting the two directives into thehttpcontext, save and close the file.

Step 2 – Edit the Nginx server block

Then open the server block configuration file.

sudo nano /etc/nginx/conf.d/seu-dominio.conf

Scroll down toLocation ~ \.php$Section. In this section, add the following lines.

fastcgi_cache phpcache;fastcgi_cache_valid 200 301 302 60m;fastcgi_cache_use_stale tempo limite of error atualizando invalid_header http_500 http_503;fastcgi_cache_min_uses 1;fastcgi_cache_lock on;add_header X-FastCGI-Cache $ upstream_cache_status;

Configure Nginx FastCGI Cache To Speed ​​Up WordPress Server Response Time - LinuxBabe (2)

  • ofastcgi_cacheThe directive allows caching using the memory zone created previously byfastcgi_cache_pathpolicy.
  • ofastcgi_cache_validsets the cache time based on the HTTP status code. In the example above, responses with status codes 200, 301, 302 are cached for 60 minutes. You can also use a dot like12h(12 hours) and7d(7 diameters).
  • Nginx can serve outdated content from its cache if it cannot get updated content from the upstream PHP FPM server. For example, when the MySQL/MariaDB database server is down. Instead of forwarding the error to clients, Nginx can serve the outdated version of the file from its cache. To enable this functionality we add thefastcgi_cache_use_staleDirectory.
  • fastcgi_cache_min_usessets the number of times clients must request an item before it is cached by Nginx. The predetermined value is 1.
  • Let's gofastcgi_cache_lockIf multiple clients request a file that is not currently in the cache, only the first such request will be allowed on the upstream PHP-FPM server. The remaining requests wait for that request to be satisfied and then pull the file from the cache. Withoutfastcgi_cache_lockenabled, all requests go directly to the upstream PHP FPM server.
  • The third line adds the X-FastCGI cache header to the HTTP response. It can be used to check if the request was served by the FastCGI cache or not.

Now save and close the server block configuration file. Then test your Nginx setup.

sudo nginx-t

If the test is successful, reload Nginx.

Reload the nginx sudo service


sudo systemctl nginx neu laden

The cache manager is now started and the cache directory (/usr/share/nginx/fastcgi_cache) is created automatically.

Testing the Nginx FastCGI cache

Reload your site's home page several times. Then use curl to get the HTTP response header.


Like this:

Configure Nginx FastCGI Cache To Speed ​​Up WordPress Server Response Time - LinuxBabe (3)

Take a look at the X-FastCGI cache header.TO DEFEATindicates that the response was served from cache.

If you always get thisLOSEcache state, you may need to add the following line in your Nginx configuration file.

fastcgi_ignore_headers cache control expires cookie set;

Like this:

fastcgi_cache phpcache;fastcgi_cache_valid 200 301 302 60m;fastcgi_cache_use_stale error timeout update invalid_header http_500 http_503;fastcgi_cache_min_uses 1;fastcgi_cache_lock on;fastcgi_ignore_headers cache control expires cookie set;add_header X-FastCGI-Cache $upstream_cache_status;

some people canHTTPS enabled on Nginx, but added the above code in the simple HTTP server block (listen 80;) and not in the HTTPS server block (listen 443 ssl;). FastCGI caching won't work if you don't add the code in the HTTPS server block.

Things that shouldn't be cached

The login session, user cookie, POST request, query string, WordPress backend, sitemap, fonts, and comment author cannot be cached. To disable caching of the above items, edit the server block configuration file. Paste the following code inServercontext, topLocation ~ \.php$Line.

set $skip_cache 0;# POST requests and URLs with a query string should always go to PHPif ($request_method = POST) { set $skip_cache 1;}if ($query_string != "") { set $skip_cache 1; }# Don Uris with the following segments are not cached if ($request_uri ~* "/wp-admin/|/xmlrpc.php|wp-.*.php|^/feed/*|/tag/.*/ feed/*| index .php|/.*sitemap.*\.(xml|xsl)") { set $skip_cache 1;}# Do not use cache for logged in users or recent commenters if ($http_cookie ~* "comment_author|wordpress_ [a- f0 - 9]+|wp-postpass|wordpress_no_cache|wordpress_logged_in") {set $skip_cache 1;}

Sometimes I want to test the response time upstream (PHP-FPM and MariaDB), so I also add the following lines to tell Nginx to bypass the FastCGI cache for my own IP addresses.

if ($remote_address ~* "|") {define $skip_cache 1;}

The tilde symbol (~) tells Nginx that the following is a regular expression (regex). the star symbol*makes the regular expression case insensitive. vertical bar|is used to toggle multiple values. If the value of$remote_addressThe variable matches each IP address in the regular expression and then sets the value of$skip_cachefor 1.

You can also bypass caching on a local network like the following, which is added10.10.10.0/24network to the ignore list.

if ($remote_address ~* "||10.10.10..*") { set $skip_cache 1; }

Note that if you use the Google XML Sitemap plugin on your WordPress site, you can probably see the following rewrite rules in your Nginx configuration.

rewrite ^/sitemap(-+([a-zA-Z0-9_-]+))?\.xml$ "/index.php?xml_sitemap=params=$2" last;rewrite ^/sitemap(-+([a -zA-Z0-9_-]+))?\.xml\.gz$ "/index.php?xml_sitemap=params=$2;zip=true" last;rewrite ^/sitemap(-+([a-zA- Z0-9_-]+))?\.html$ "/index.php?xml_sitemap=params=$2;html=true" last;rewrite ^/sitemap(-+([a-zA-Z0-9_-]+ ))?\.html.gz$ "/index.php?xml_sitemap=params=$2;html=true;zip=true" zuletzt;

These rewrite rules should be placed below the skip cache rules. If the rewrite rules are above the cache bypass rules, your sitemap will always be cached. Similarly, if you use the Yoast SEO plugin to generate the sitemap, you should also move the Yoast rewrite rules to the bypass cache rules.

Not nowLocation ~ \.php$section, paste the following statements.

fastcgi_cache_bypass $skip_cache;fastcgi_no_cache $skip_cache;

If the value of$skip_cacheis 1, so the first directive tells Nginx to send the request to the upstream PHP FPM server instead of trying to find files in the cache. The second directive tells Nginx not to cache the response. Save the file and reload Nginx.

sudo systemctl nginx neu laden


Reload the nginx sudo service

How to Clear Cache Automatically with WordPress

First you need to install and activate it.Nginx helper namePlugin on your WordPress site. Then go to WordPressIdeas->nginx helperand mark noenable deleteBox. The default purge conditions are fine for most WordPress blogs. You can also enable logging to verify that the cleanup is working correctly.

Configure Nginx FastCGI Cache To Speed ​​Up WordPress Server Response Time - LinuxBabe (4)

click notsave all changesGusto.

So you need to installhttp cache cleaningmodule on your Linux server. Run the following command to install it on Ubuntu 18.04 and later. A configuration file is included during the installation process./etc/nginx/modules-enabled/Directory to enable this module.

sudo apt install libnginx-mod-http-cache-purge

You can also installnginx-Extraspackage to enable this module, but this package also enables many other modules. To keep my nginx as light as possible, I don't install itnginx-ExtrasPackage.

Then open the Nginx server block configuration file. Add the following linesserver {...}Context.

ubicación ~ /purge(/.*) { fastcgi_cache_purge phpcache "$scheme$request_method$host$1";}

Save and close the file. Then test your Nginx setup.

sudo nginx-t

If the test is successful, reload Nginx.

sudo systemctl nginx neu laden

You can now modify one of your WordPress posts to see if the cache is cleared automatically.

Nginx Cache Sniper-Plugin

If the Nginx helper plugin doesn't work, you can also use itNginx-Cache-SniperPlugin on your WordPress site. Install the plugin and go toPainel hace WordPress->Tool->Nginx-Cache-Sniperto configure it.

Configure Nginx FastCGI Cache To Speed ​​Up WordPress Server Response Time - LinuxBabe (5)

How to preload the cache

You can cache the page before visitors arrive on your site. The Nginx FastCGI cache does not provide a way to preload the cache. However, you can use thewgetTool in another box to download the entire website, forcing Nginx to create a cache for each web page.

wget -m -p -E -k

Make sure the other box's IP address is not on the bypass list. wget creates awww.seudominio.comdirectory and save the content there.

Sometimes I need to clear and regenerate the Nginx FastCGI cache, but I don't want to write the file manuallywgetcommand every time. So I created a cronjob to automate this task.

crontab -e

Add the following line to the end of the crontab file./tmp/ramdisk/It's aDisco-RAMI created it to store the files so the content would be written to RAM and my SSD wouldn't wear out quickly.

@por hour rm /tmp/ramdisk/; wget -m -p -E -k -P /tmp/ramdisk/

Save and close the file. (I know this is not a very good way to solve the problem, but it does get the job done.)

How to set up FastCGI caching for multiple WordPress sites

If you have multiple instances of your WordPress site installed on the same server, you can create a separate FastCGI cache for each WordPress site.

sudo nano /etc/nginx/nginx.conf

Like this:

fastcgi_cache_path /usr/share/nginx/dominio1_fastcgi_cachelevel=1:2 keys_zone=dominio1:100m max_size=10g inativo=60m use_temp_path=off;fastcgi_cache_path /usr/share/nginx/domain2_fastcgi_cachelevel=1:2 keys_zone=dominio2:100m max_size=10g inativo=60m use_temp_path=off;fastcgi_cache_key "$scheme$request_method$host$request_uri";

Every WordPress site uses a unique key zone. There are two main areas in the above codedominio1midominio2. Now the Nginx virtual host file should be used for domain 1

ubicación ~ \.php$ { fastcgi_pass unix:/run/php/php8.1-fpm.sock; fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name; incluir fastcgi_params; agregue fragmentos/fastcgi-php.conf; fastcgi_cachedominio1; fastcgi_cache_bypass $skip_cache; fastcgi_no_cache $skip_cache; fastcgi_cache_valid 200 301 302 60m; Fastcgi_cache_use_stale Timeout-Fehler beim Actualisieren von invalid_header http_500 http_503; fastcgi_cache_min_uses 1; fastcgi_cache_lock an; add_header X-FastCGI-Cache $upstream_cache_status; } ubicación ~ /purga(/.*) { fastcgi_cache_purgedominio1"$esquema$request_method$host$1"; }

And the Nginx virtual host file for domain2 should use:

location ~ \.php$ { fastcgi_pass unix:/run/php/php8.1-fpm.sock; fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name; include fastcgi_params; add fragments/fastcgi-php.conf; fastcgi_cache domain2; fastcgi_cache_bypass $skip_cache; fastcgi_no_cache $skip_cache; fastcgi_cache_valid 200 301 302 60m; Fastcgi_cache_use_stale timeout error while updating invalid_header http_500 http_503; fastcgi_cache_min_uses 1; fastcgi_cache_lock set; add_header X-FastCGI-Cache $upstream_cache_status; } location ~ /purga(/.*) { fastcgi_cache_purgedominio2"$esquema$request_method$host$1"; }

Next step

I hope this article has helped you to set up Nginx FastCGI Cache with WordPress. You may also want to useNginx amplification nameto monitor the performance of the LEMP stack.

  • Monitoring LEMP stack performance with Nginx Amplify on Ubuntu 18.04/16.04

And if site security is important to you, you can set it upModSecurity Web Application Firewallto protect your WordPress site from hackers.

  • How to configure ModSecurity with Nginx on Debian/Ubuntu

You may also want to use thosePage speed of the Nginx moduleto optimize the performance of the website interface.

  • Install Nginx PageSpeed ​​module on Ubuntu 20.04/18.04 server

As always, if you have found this post useful.Subscribe to our free newsletterfor more tips and tricks. take care 🙂

The grade is tutorial



How do I enable FastCGI in nginx? ›

Add PHP support to Nginx
  1. Add index. php to the index list.
  2. Uncomment the PHP scripts to FastCGI entry block.
  3. Uncomment the line to include snippets/fastcgi-php. conf.
  4. Uncomment the line to enable the fastcgi_pass and the php8. 1-fpm. sock.
  5. Uncomment the section to deny all access to Apache . htaccess files.
May 27, 2022

How do I enable Nginx caching in WordPress? ›

Go to the “Web Server” tab. In the “nginx settings” section, select the “Enable nginx caching” checkbox. (Optional) You can customize nginx caching settings. If you are not familiar with nginx caching, we recommend that you keep the default settings.

What is Nginx FastCGI cache? ›

FastCGI (the protocol used to communicate between Nginx and PHP-FPM) caching will be configured to cache responses from PHP-FPM as static HTML files, which Nginx can directly serve on subsequent requests. As you can see, they're not exactly the same in functionality.

How does nginx cache work? ›

By default, NGINX Plus caches all responses to requests made with the HTTP GET and HEAD methods the first time such responses are received from a proxied server. As the key (identifier) for a request, NGINX Plus uses the request string.

How do I enable FastCGI in Linux? ›

Installing mod_fastcgi manually
  1. Copy or move the mod_fastcgi distribution directory to /src/modules/fastcgi.
  2. Add the FastCGI module to /src/Configuration. ...
  3. From the /src directory, reconfigure and rebuild Apache. ...
  4. Edit the httpd configuration files to enable your FastCGI application(s). ...
  5. Stop and start the server.

Which is better FastCGI or FPM? ›

FPM processes requests faster (more than 30%) compared to FastCGI, which also allows it to process more than 30% more requests at a time than FastCGI. FPM helps improve visitor experience and search engine ranking due to its 5+ times shorter TTFB (Time To First Byte).

Is Nginx good for WordPress? ›

Both Apache and NGINX work well with WordPress hosting. However, NGINX might be the better option if you want improved performance. Let's take a look at how to install WordPress on both types of servers, so you'll be ready to get started with either one.

How do I fix WordPress caching problems? ›

Hard Refresh Your Web Browser

The simplest solution to fix browser caching issues on a single page is to hard-refresh your web browser. When you force a hard refresh, your browser will skip the cache and download all web server assets.

Can you use nginx with WordPress? ›

Nginx supports reverse proxy, caching, media streaming, load balancing and much more. That makes it a great fit for a WordPress website powered by a VPS. Few of Nginx's inbuilt features are: Nginx is built to work on low memory usage.

What is the difference between Nginx Fastcgi_cache and Proxy_cache? ›

The difference between the two is the protocol used to communicate with the backend. fastcgi_cache is related to the FastCGI backend protocol. It caches output from FastCGI connected backends. proxy_cache is related to backends that use HTTP as the backend protocol, and it caches output from HTTP connected backends.

When should I use FastCGI? ›

Nginx fastcgi is used to efficiently interface the process of server request with the content of dynamic. Nginx fastcgi is used to translate the request of the client from the application server which was not handled by the request of the client directly.

What is the default FastCGI timeout for Nginx? ›

The problem is that Nginx waits by default for 60s on the fastCGI response. If it takes too long, the request is stopped. The “Connection timed out” error means that Nginx hit a timeout before it received a response from the FastCGI backend.

What is the default cache time for nginx? ›

The default value is 10 minutes ( 10m ). Inactive content differs from expired content. NGINX does not automatically delete content that has expired as defined by a cache control header ( Cache-Control:max-age=120 for example).

What is the maximum cache size in nginx? ›

Nginx can store roughly 8000 entries for each megabyte. The max_size parameter specifies the maximum size of the actual cached data, 50MB for our example. You should also notice the proxy_cache_key directive used. This directive specifies the key that we will use to store cached values.

How to set Cache-Control in nginx? ›

If you want to enable Cache-Control for all files, add a add_header line without the enclosing location block, as what the location block does is specify specific filetypes you are targeting with your directives (ico,pdf,flv etc.).

How do I set up FastCGI? ›

On the server level, double-click FastCGI Settings. Select the FastCGI application that you want to configure. In the Actions pane, click Edit. In the Edit FastCGI Application dialog box, set the InstanceMaxRequests to 10000.

Is FastCGI still being used? ›

FastCGI remains the preferred choice over CGI and other proprietary server application programming interfaces (APIs) because its features are fast, open and maintainable. However, FastCGI remains a proposed open standard and is not yet widely used.

Does FastAPI use nginx? ›

Generally, FastAPI's are deployed using uvicorn which is a lightning-fast ASGI server implementation. Another way of deploying is using NGINX Unit which is a lightweight, open-source app server designed for today's dynamic and distributed apps.

What is the difference between CGI and FastCGI? ›

What makes a difference from CGI is that with FastCGI the running process of the application lasts longer and it is not immediately terminated. After the application finishes processing and returns the output data, the process is not terminated and is being used for processing further requests.

How to increase PHP-FPM memory limit? ›

For example, to increase the PHP memory limit:
  1. Edit the main PHP configuration file at /opt/bitnami/php/etc/php.ini and set the memory_limit variable to a new value, as shown below: memory_limit=NEW_LIMIT.
  2. Modify the PHP-FPM pool configuration file and set the corresponding variable as follows.


Top Articles
Latest Posts
Article information

Author: Jerrold Considine

Last Updated: 16/09/2023

Views: 6077

Rating: 4.8 / 5 (78 voted)

Reviews: 85% of readers found this page helpful

Author information

Name: Jerrold Considine

Birthday: 1993-11-03

Address: Suite 447 3463 Marybelle Circles, New Marlin, AL 20765

Phone: +5816749283868

Job: Sales Executive

Hobby: Air sports, Sand art, Electronics, LARPing, Baseball, Book restoration, Puzzles

Introduction: My name is Jerrold Considine, I am a combative, cheerful, encouraging, happy, enthusiastic, funny, kind person who loves writing and wants to share my knowledge and understanding with you.