100,000+ websites use our FREE WordPress plugins!  Download Now 36+ FREE WordPress plugins!  Browse Here

How to Setup FastCGI Caching on Nginx Servers

   |  21 Jan, 2017

A few years back, it had already become apparent that Nginx was the brave new king of web servers, due to its impressive simplicity and ability to scale with ease. One of its most attractive features, however, was its ability to act as a “reverse proxy” either in front of an Apache server, or even just completely on its own.

The only issue that really remained was whether FastCGI caching or true “proxy” caching (via proxy_pass) was the way forward, so naturally, fanboys on both sides duked it out for a few years there (okay, not really). TL;DR: FastCGI is meant to be an internal protocol, while proxy_pass is just the HTTP protocol being, well, sort of extended on the backend.

Now, it is safe to say beyond a doubt that FastCGI has won out, and for good reason…

First, if you already installed Nginx, you should remove it:

sudo apt-get update
sudo apt-get remove nginx*

Note: A fresh install of nginx-extras is always the better approach whenever possible.

Next, we will install the nginx-extras version of Nginx, and make sure its on the mainline (development) branch for newest features and compatibility (i.e. HTTP/2, etc).

sudo apt-get update
sudo add-apt-repository ppa:nginx/development
sudo apt-get update
sudo apt-get install nginx-extras
sudo apt-get update
sudo apt-get upgrade

Note: Make sure that your nginx.conf file has the below line before proceeding:

include /etc/nginx/modules-enabled/*.conf;

Now it’s time to edit your server block:

sudo nano /etc/nginx/sites-available/default

Include the following configuration in your Nginx server block:

#### below lines must be outside server blocks to enable FastCGI cache for Nginx
#### path can be anywhere, app name must be consistent, total size small enough to avoid RAM depletion
fastcgi_cache_path /etc/nginx/cache levels=1:2 keys_zone=WORDPRESS:128m inactive=30m;
fastcgi_cache_key "$scheme$request_method$host$request_uri";
fastcgi_cache_use_stale error timeout invalid_header http_500;
fastcgi_ignore_headers Cache-Control Expires Set-Cookie;
add_header X-FastCGI-Cache $upstream_cache_status;

## this block redirects all HTTP non-www to HTTP www version
server {
    server_name            www.cyber-breeze.com;
    listen                 *:80;
    listen                 [::]:80 ipv6only=on;
    return 301 http://cyber-breeze.com$request_uri;
}

## this block is the default configuration for the live website
server {
    server_name            cyber-breeze.com;
    listen                 *:80 default_server;
    listen                 [::]:80;
    root                   /home/cyber/www;
    index index.php;
    autoindex off;

    set $skip_cache 0;

    # POST requests and URLs with a query string should always go to PHP
    if ($request_method = POST) {
        set $skip_cache 1;
    }

    if ($query_string != "") {
        set $skip_cache 1;
    }

   # Don't cache URIs containing the following segments
    if ($request_uri ~* "/wp-admin/|wp-.*.php|/feed/|index.php|sitemap(_index)?.xml") {
        set $skip_cache 1;
    }

    # Don't use the 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;
    }

    location / {
        try_files $uri $uri/ /index.php?$args;
    }

   ## make sure PHP loads via FCGI for better performance
    location ~ \.php$ {
        try_files $uri =404;
        #### or use 'include fastcgi_params' for older Nginx versions
        include fastcgi.conf;
        #### substitute the socket, or address and port, of your WordPress server i.e. fastcgi_pass 127.0.0.1:9000;
        fastcgi_pass unix:/run/php/php7.0-fpm.sock;
        fastcgi_index index.php;
        fastcgi_cache WORDPRESS;
        fastcgi_cache_valid 200 301 302 404 60m;
        fastcgi_cache_bypass $skip_cache;
        fastcgi_no_cache $skip_cache;
    }

    location ~ /purge(/.*) {
	    fastcgi_cache_purge WORDPRESS "$scheme$request_method$host$1";
    }	

    #### add more: http://mirrors.littlebizzy.com/nginx/nginx-server-block-ssl.txt

}

https://www.digitalocean.com/community/tutorials/how-to-setup-fastcgi-caching-with-nginx-on-your-vps
https://www.nginx.com/blog/9-tips-for-improving-wordpress-performance-with-nginx/#cache-dynamic
https://easyengine.io/wordpress-nginx/tutorials/single-site/fastcgi-cache-with-purging/
https://www.howtoforge.com/why-you-should-always-use-nginx-with-microcaching
https://www.linuxbabe.com/nginx/setup-nginx-fastcgi-cache
https://www.scalescale.com/tips/nginx/configure-nginx-fastcgi-cache/

Shout out to Jesin A. for his helpful discussions with me that improved this article.

Tags: , , ,

Last modified:  11 Mar, 2017
http://bizzy.in/2iMIx07

13 comments on "How to Setup FastCGI Caching on Nginx Servers":

  1. Will you help a dummy?

    — ## make sure PHP loads via FCGI for better performance
    include fastcgi.conf; – is the file containing all this code, right?

    — fastcgi_cache_valid 200 301 302 404 60m;
    Does this mean that the cache will be auto-purged? Could it be purged on demand?

    Thanks.

    • Hello Chip,

      If you use an Nginx server block like above, it will load PHP-FPM via FCGI.

      Yes, you can purge Nginx cache using a WordPress plugin:

      https://wordpress.org/plugins/nginx-cache/

      • Can I ask you something else?
        Since I’m new to all this, I will be using Webuzo to manage my new server.
        New .conf files can be added via the panel. For pretty links I’m using this code:

        try_files $uri $uri/ /index.php?q=$uri&$args;

        Only that line of code used, “location /” not used.

        In case of forcing https:

        if ($scheme = http) {
        return 301 https://$server_name$request_uri;
        }

        In this case, should I use your code above as it is? Just copy/paste?

        And if I manage to implement all this, how can I test it to know it’s working?

        Thank you.

      • The above block is a bit outdated compared to what we use now.

        You may wish to watch out for our upcoming LEMP automation project, SlickStack:

        https://slickstack.io

  2. Guess bad luck for me since my server has CentOS installed. I’ll stick around maybe you will post updates :)
    Cheers.

  3. Hello, I am trying to configure fastCGI cache with nginx, but it does not save anything in the destination folder / var / cache / nginx. Is it possible that because I use CDN I’m not frisking anything?

    regards

    • I’m not sure what you mean by frisking but a CDN should only affect static resources whereas FastCGI Cache saves cache files for each page loaded on your site.

      If nothing is being saved, double check your Nginx config.

  4. Can I use your https://www.littlebizzy.com/slickstack#installation

    to install an optimized WordPress with nginx configured or still i have to make some changes?

    and object cache is needed or not?

    or serving full static page will do the magic

    • Yes, SlickStack will offer pre-optimized LEMP configs.

      Object cache is not recommended for most WordPress sites, but SlickStack will support Redis out of the box (as a key-value pair store only, not a full-page cache).

      FastCGI cache via Nginx is the page cache.

      • How can i access Phpmyadmin and file manager when i will install using https://www.littlebizzy.com/slickstack#installation

        and

        Just using this command sudo wget mirrors.littlebizzy.com/slickstack/installer && sudo bash ss

        will install WordPress and nginx php phofpm and Maria db and which version does it will install?

        is there any post where you demonstrate it would be appreciated

  5. and i dont think there will be need of caching plugin
    there is nginz to do the work
    sorry im new to all these things

  6. Hi Jesse I Know You are busy guy can you link to any website where i can learn about it

    The Problem is i want to move my site to vultr or any other alternative because my host have some restrictions on how many files i can save

    So if i use cpanel like server pilot or its alternative it will eat alot of cpu and ram and if i use your bash script so i dont know how can i access Phpmyadmin and files

    can you tell me how can i access Phpmyadmin and file manager?

  7. can you tell me which software does SlickStack install on my server?

    as you tell above in comment about lemp that means it has linux nginx and mysql and php

    is there any other software does it install?

    and does i have to Setup FastCGI Caching on Nginx Servers or it comes pre-configured?

Leave a Reply

Your email address will not be published.*


FREE Facebook group