How to Improve WordPress Performance with Nginx FastCGI and PHP-FPM on Ubuntu Linux

|

|

The tutorial provides steps on enhancing the speed of WordPress sites by setting up WordPress with Nginx and FastCGI. The technique involves installing the Nginx HTTP server and enabling FastCGI caching. The method allows FastCGI modules to cache dynamic PHP content, speeding up content delivery on PHP-based applications, including WordPress. Additionally, the tutorial guides users…

Almost all webmasters will want their websites and blogs to be the fastest. However, making your users happy when they visit your sites should be your priority as a web admin.

The steps below will show students and new users how to set up WordPress with Nginx and FastCGI to perform faster, even with a single server. To improve your WordPress site performance, install the Nginx HTTP server and enable FastCGI caching. Doing this will significantly improve WordPress performance.

This brief tutorial will show students and new users how to install the Nginx HTTP server and enable FastCGI on Ubuntu 16.04 LTS with PHP 7.2-FPM.

Combining the Nginx web server and FastCGI module will significantly improve your PHP-based applications, including WordPress websites. FastCGI module caches dynamic PHP content that is served through the Nginx backend.

When dynamic PHP content is cached, repeated requests for the same content are quickly returned from the cache store instead of compiling all the dynamic data that make up the page each time a request is made.

So, when running a website or blog powered by Nginx, include FastCGI caching.

Install Nginx Latest Version

First, install Nginx from the Ubuntu default repository. This will install a stable version of the Nginx HTTP server.

sudo apt install nginx

However, if you want to install or upgrade to the latest version of Nginx, then run the commands below.

cd /tmp/ && wget http://nginx.org/keys/nginx_signing.key

After adding the key, run the commands below to install Nginx’s Mainline repository or branch on Ubuntu.

sudo sh -c "echo 'deb http://nginx.org/packages/mainline/ubuntu/ '$(lsb_release -cs)' nginx' > /etc/apt/sources.list.d/NginxMainline.list"

When you’re done, you must run the commands below to install the latest version of Nginx.

sudo apt-get update
sudo apt-get install nginx

The commands above will upgrade to the latest version of the Nginx HTTP server.

After installing Nginx, the commands below can be used to stop, start and enable the Nginx service to always start up with the server boots.

sudo systemctl stop nginx.service
sudo systemctl start nginx.service
sudo systemctl enable nginx.service

Install PHP 7.2-FPM and Related Modules.

PHP 7.2 may not be available on Ubuntu default repositories… to install it, you will have to get it from third-party repositories.

Run the commands below to add the below third party repository to upgrade to PHP 7.2-FPM

sudo apt-get install software-properties-common
sudo add-apt-repository ppa:ondrej/php

Then update Ubuntu by running the commands below.

sudo apt update

Then run the commands below to install PHP 7.2-FPM and related modules.

sudo apt install php7.2-fpm php7.2-common php7.2-mbstring php7.2-xmlrpc php7.2-gd php7.2-xml php7.2-mysql php7.2-cli php7.2-zip php7.2-curl

After installing PHP 7.2-FPM, run the commands below to open PHP 7.2-FPM default file.

sudo nano /etc/php/7.2/fpm/php.ini

Then save the changes on the following lines below in the file. The value below is an excellent setting to apply in your environment.

file_uploads = On
allow_url_fopen = On
memory_limit = 256M
upload_max_filesize = 100M
cgi.fix_pathinfo = 0
max_execution_time = 360
date.timezone = America/Chicago

After installing and updating, the commands below can be used to stop, start and enable PHP 7.2-FPM to always startup when the server boots.

sudo systemctl stop php7.2-fpm.service
sudo systemctl start php7.2-fpm.service
sudo systemctl enable php7.2-fpm.service

Setup FastCGI Directive in Nginx.conf file.

Nginx configuration files are stored in the /etc/Nginx directory on Ubuntu systems. In that directory, Nginx’s primary configuration file, Nginx.conf, is also stored there. In that file is where you set up Nginx global configurations.

In Nginx main configuration file at /etc/nginx/nginx.conf, place the block of code before the last line in the file and save.

Run the commands below to open the file.

sudo nane /etc/nginx/nginx.conf

Then copy and paste the block of lines below into the file and save. Then close out

## Nginx FastCGI Cache
    fastcgi_cache_path /var/cache/nginx/fastcgi_temp/cache levels=1:2 keys_zone=cachezone:10m max_size=2g inactive=60m use_temp_path=off;
    fastcgi_cache_key $scheme$request_method$host$request_uri;
    fastcgi_cache_lock on;
    fastcgi_cache_revalidate on;
    fastcgi_cache_background_update on;
    fastcgi_cache_use_stale error timeout invalid_header updating http_500;
    fastcgi_cache_valid any 60m;
    fastcgi_pass_header Set-Cookie;
    fastcgi_pass_header Cookie;
    fastcgi_ignore_headers Cache-Control Expires Set-Cookie;
    include /etc/nginx/conf.d/*.conf;
    include /etc/nginx/sites-enabled/*;

Save the file when done.

Setup FastCGI Directive in Nginx Web config file.

On Ubuntu systems, Nginx individual website configuration files or virtual host files are stored in /etc/nginx/sites-available/

That is where you store your website configurations. There should already be a default configuration file there. When implementing FastCGI for a website, open the site configuration file and edit the PHP block, as shown below.

Run the commands below to open the default site configuration file.

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

Then make the PHP block look like the one below and save.

location ~ \.php$ {
         include snippets/fastcgi-php.conf;
         fastcgi_pass unix:/var/run/php/php7.2-fpm.sock;
         fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
         fastcgi_cache_bypass $skip_cache;
         fastcgi_no_cache $skip_cache;
         fastcgi_cache cachezone;
         include fastcgi_params;
         fastcgi_buffer_size 128k;
         fastcgi_connect_timeout 60s;
         fastcgi_send_timeout 60s;
         fastcgi_read_timeout 60s;
         fastcgi_buffers 256 16k;
         fastcgi_busy_buffers_size 256k;
         fastcgi_temp_file_write_size 256k;
    }

Save the file when you’re done.

PHP should go through the FastCGI module and enable caching if everything is set up correctly.

For the WordPress website, you should include the code block below in the site configuration file, just above the location ~\.php$ block.

set $skip_cache 0;
   # POST requests and url's with a query string should always skip cache
    if ($request_method = POST) {
        set $skip_cache 1;
    }
    if ($query_string != "") {
        set $skip_cache 1;
    }
    # Don't cache url's containing the following segments
    if ($request_uri ~* "/wp-admin/|/xmlrpc.php|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;
    }

Save the file, and you’re done.

Reload Nginx and you’re done.

sudo systemctl restart  nginx.service
sudo systemctl restart php7.2-fpm.service

This is how to enable FastCGI support for Nginx. It’s our best setting, and it works on all our sites. It’s great. It would be best if you tried it.

You may also like the post below:

Like this:



6 responses to “How to Improve WordPress Performance with Nginx FastCGI and PHP-FPM on Ubuntu Linux”

  1. Vdo Avatar
    Vdo

    Nice, site speed +++
    Again thanks!

  2. Kent Avatar
    Kent

    Hello. Thank for your post. But i have problem when i pass this code to nginx.conf file:

    Nginx FastCGI Cache

    fastcgi_cache_path /var/cache/nginx/fastcgi_temp/cache levels=1:2 keys_zone=cachezone:10m max_size=2g inactive=60m use_temp_path=off;
    fastcgi_cache_key $scheme$request_method$host$request_uri;
    fastcgi_cache_lock on;
    fastcgi_cache_revalidate on;
    fastcgi_cache_background_update on;
    fastcgi_cache_use_stale error timeout invalid_header updating http_500;
    fastcgi_cache_valid any 60m;
    fastcgi_pass_header Set-Cookie;
    fastcgi_pass_header Cookie;
    fastcgi_ignore_headers Cache-Control Expires Set-Cookie;
    include /etc/nginx/conf.d/*.conf;
    include /etc/nginx/sites-enabled/*;

    And my nginx don’t work. Can you help me?

    1. ErnestPH Avatar
      ErnestPH

      same here… this tutorial is not working. get stuck at the same step… error is:

      nginx: [emerg] “fastcgi_cache_path” directive is not allowed here in /etc/nginx/nginx.conf:2

    2. ErnestPH Avatar
      ErnestPH

      Kent, in this tutorial you have to do some steps to make it successful…

      create the folder (using root user) – /var/cache/nginx/fastcgi_temp/ (to avoid the error)
      the code from ## Nginx FastCGI Cache should be added inside http {} block

      these steps weren’t pointed out hence the confusion. But it should work now!

  3. Don Avatar
    Don

    hi,
    Can’t seem to get this working on 18.0.4 LTS, NGINX & PHP 7.3. Anytime I make changes it breaks NGINX. The error related to the cache directory. Any ideas to fix and verify caching is working? phpinfo.php file also does not work until I made the following change:

    /etc/nginx/sites-enabled/default

    location ~ .php$ {
    fastcgi_pass unix:/var/run/php/php7.3-fpm.sock;
    fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
    include fastcgi_params;
    }

  4. Don Knots Avatar
    Don Knots

    hi,
    Can’t seem to get this working on 18.0.4 LTS, NGINX & PHP 7.3. Anytime I make changes it breaks NGINX. The error related to the cache directory. Any ideas to fix and verify caching is working? phpinfo.php file also does not work until I made the following change:

    /etc/nginx/sites-enabled/default

    location ~ .php$ {
    fastcgi_pass unix:/var/run/php/php7.3-fpm.sock;
    fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
    include fastcgi_params;
    }

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.