Atlantic.Net Blog

How to Setup Nginx Cache on LEMP Server

Nginx is free, open-source web server, not to mention one of the most widely used web servers in the world. It can be used as a reverse proxy, mail proxy, load balancer and caching server. Nginx is highly scalable and specially designed for maximum performance and stability. It uses an event-driven architecture and handles every incoming request in a single thread.

Nginx comes with a FastCGI module that can be used to cache dynamic content served from the PHP backend. You don’t need to set up other caching solutions such as Redis, Varnish, Memcache after setting up Nginx with FastCGI cache.

In this tutorial, we will show you how to set up Nginx FastCGI cache with LEMP on Ubuntu 18.04.


Step 1 – Install LEMP Server

Let’s start with installing LEMP (Nginx, PHP, PHP-FPM) on your server.

apt-get install nginx php php-cli php-fpm -y

The above command will also install Apache web server in your system, so you will need to stop and disable the Apache service.

systemctl stop apache2
systemctl disable apache2

Next, start the Nginx and PHP-FPM service with the following command:

systemctl start nginx
systemctl start php7.2-fpm

Once you are finished, you can proceed to the next step.

Step 2 – Create a Sample Website

First, create a directory for your website with the following command:

mkdir /var/www/html/example.com

Next, create a sample info.php file inside your website directory:

nano /var/www/html/example.com/info.php

Add the following lines:

<?php phpinfo(); ?>

Save and close the file. Then, change the ownership of your website to www-data user:

chown -R www-data:www-data /var/www/html/example.com
chmod -R 755 /var/www/html/example.com

Once you are finished, you can proceed to the next step.

Step 3 – Configure Nginx with FastCGI Cache

Next, you will need to create a new Nginx virtual host configuration file to serve your website and enable the FastCGI cache.

nano /etc/nginx/sites-available/example.com.conf

Add the following lines:

# Enable FastCGI Support
fastcgi_cache_path /etc/nginx/cache levels=1:2 keys_zone=nginxcache:150m max_size=1g 
inactive=60m use_temp_path=off;
fastcgi_cache_key "$scheme$request_method$host$request_uri";
add_header X-Cache $upstream_cache_status;

server {
listen 80;
root /var/www/html/example.com;
client_max_body_size 256M;
index info.php;
server_name example.com;
access_log /var/log/nginx/access.log;
error_log /var/log/nginx/error.log;
location = /favicon.ico { access_log off; log_not_found off; }

#Disable caching for login session, user cookie, POST request, query string, site map and feeds
set $skip_cache 0;
if ($request_method = POST) {
set $skip_cache 1;
}
if ($query_string != "") {
set $skip_cache 1;
}

# Enable caching for your website.
location ~ \.php$ {
fastcgi_split_path_info ^(.+\.php)(/.+)$;
fastcgi_pass unix:/var/run/php/php7.2-fpm.sock;
fastcgi_index info.php;
include fastcgi_params;
fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
fastcgi_intercept_errors off;
fastcgi_buffer_size 16k;
fastcgi_buffers 4 16k;
fastcgi_connect_timeout 600;
fastcgi_send_timeout 600;
fastcgi_read_timeout 600;
fastcgi_cache nginxcache;
fastcgi_cache_valid 200 301 302 60m;
fastcgi_cache_use_stale error timeout updating invalid_header http_500 http_503;
fastcgi_cache_min_uses 1;
fastcgi_cache_lock on;

}
}

Save and close the file when you are finished, then check Nginx for any syntax errors with the following command:

nginx -t

You should get the following output:

Next, enable the Nginx virtual host file with the following command:

ln -s /etc/nginx/sites-available/example.com.conf /etc/nginx/sites-enabled/

Finally, reload the Nginx service to apply the changes:

systemctl restart nginx

A brief explanation of each directive in the above configuration file is shown below:

  • fastcgi_cache_path creates a FastCGI cache and specifies the cache location, memory zone name (nginxcache) with size (150M), max_size (1G), and defines the key for cache lookup.
  • add_header is used to validate whether the request has been served from the FastCGI cache or not.
  • fastcgi specifies the path of the php-fpm socket.
  • fastcgi_cache enables caching, which we have specified using the memory zone in fastcgi_cache_path directive.
  • fastcgi_cache_valid sets the cache time with status code 200, 301, 302 will be cached for 60 minutes.
  • fastcgi_cache_lock allows only first request through the upstream PHP-FPM server.

Step 4 – Test Nginx FastCGI Cache

At this point, Nginx is installed and configured with FastCGI Cache support. It’s time to verify whether the caching is working or not.

Open your web browser, access your Nginx web server using the URL http://example.com, and reload the page a few times.

Next, open your terminal and run the following command to fetch the http response header.

curl -I http://example.com

You should get the following output:

HTTP/1.1 200 OK
Server: nginx/1.14.0 (Ubuntu)
Date: Fri, 24 Apr 2020 16:07:24 GMT
Content-Type: text/html; charset=UTF-8
Connection: keep-alive
X-Cache: HIT

From the above output, X-Cache: HIT indicates that the response was served from the cache.

Conclusion

Congratulations! You have successfully configured Nginx with FastCGI Cache support. After enabling caching, you should notice a huge improvement in performance because pages are loaded without having to be rendered by PHP. Try out FastCGI Cache on Nginx today with Atlantic.Net’s VPS hosting service.

Get a $250 Credit and Access to Our Free Tier!

Free Tier includes:
G3.2GB Cloud VPS a Free to Use for One Year
50 GB of Block Storage Free to Use for One Year
50 GB of Snapshots Free to Use for One Year