Nginx Caching: How to Use Nginx for Caching Static Content

Nginx Caching: How to Use Nginx for Caching Static Content. In this guide, we introduce Nginx and how to use it to cache static content.

The primary purpose of designing Nginx Cache was to address the speed issues that web platforms and apps deal with on a regular basis. Nginx provides a massively scalable caching solution to efficiently deliver static and infrequently changing content to a wide range of customers.

What is Caching in Nginx?

Caching is the process of storing data locally to facilitate faster data transfer between a client and a web server. Utilizing caching enables optimal reuse of previously acquired or computed data. Found individually on the client side, server side, or in both areas. With caching, users can faster access repetitive requests.

In simple terms, a cache is any site that temporarily stores copies of files or other data. For faster loading of websites, web browsers cache or create copies of HTML files, images and JavaScript. DNS servers, on the other hand, caches all DNS records. Similarly, there are CDN servers that cache content to decrease latency. So, how exactly does a cache work?

Each time a user makes an attempt to load a webpage, the amount of data that must be downloaded by a user’s browser is substantial. Browsers save a copy of the web page’s content visible on the screen on the device’s hard drive. By doing this, much of the data will already be locally stored when the user loads the website the following time, making it load considerably faster. These files are kept by browsers until the hard drive cache is full or until their time to live (TTL) runs out.

The central storage location, which may be directly linked to the caching server or connected via a network, is checked if the requested information is not already in the cache. Caching algorithms are used to assess whether it is likely to be requested again after it has arrived at the server. If so, the information is provided to the client and added to the cache.

How Does Caching in Nginx Help?

Nginx is one of the best load‑balancing solutions in the market that helps deliver content faster and securely. Over 350+ millions of platforms, including Netflix, Dropbox, etc. use Nginx over Apache and other web server. Caching in Nginx is the technique of creating copies of frequently accessed data in a disk or memory. This method helps lighten the strain on the web server and enhance the general performance of online applications.

Additionally, dynamic replies received from scripting languages using protocols like FastCGI, SCGI are easily handled by the Nginx Plus caching server. It even provides access to live activity monitoring functions that allow users to track and evaluate how well your content caches are being used.

The built in caching features of Nginx are used to cache both static as well as dynamic information. It even helps reduce server load and response times.

Nginx’s caching can be adjusted and altered based on a number of factors, including cache size, duration, rules for clearing the cache, and how the cache behaves with regard to certain resource types. To achieve the best speed advantages, it is crucial to correctly tune the cache settings based on the unique requirements of the application.

Nginx Caching: How to Use Nginx for Caching Static Content

In this section, we show you how to install and configure Nginx to cache static content.

Prerequisites

  • A root user or a user with sudo privileges.

Update System Packages

First, I would recommend updating and upgrading all of your system packages to the latest version. Run the following command to update all those packages.

				
					apt update -y
apt upgrade -y
				
			

Once all the system packages are up to date, proceed to the next step.

Install Nginx and PHP

Next, you will need to install Nginx and PHP on your server. You can install all of them using the following command.

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

After installing all of those packages, start both Nginx and PHP-FPM services and enable them to start at system reboot.

				
					systemctl start nginx php8.1-fpm
systemctl enable nginx php8.1-fpm
				
			

Then, verify the status of the Nginx using the following command.

				
					systemctl status nginx
				
			

If everything is fine, you will see the following screen.

At this point, Nginx is installed and running. Now, let’s verify the default Nginx configuration for caching.

				
					curl -I http://localhost
				
			

You can see that there is not any cache configured on your Nginx server.

Create a Directory Structure For Nginx

Before configuring Nginx caching, create a directory and sample PHP page to test the caching.

First, create a document root directory using the following command.

				
					mkdir /var/www/html/web1.example.com
				
			

Next, create a sample PHP page with the following command.

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

Add the following PHP code.

				
					<?php phpinfo(); ?>
				
			

Save and close the file then set proper permission and ownership on the Nginx document root directory.

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

Next, create a directory to store the Nginx cache and set the Nginx ownership on it.

				
					mkdir /etc/nginx/cache
chown -R www-data:www-data /etc/nginx/cache
				
			

Configure Nginx to Cache Static Content

Now, create an Nginx configuration file to cache the static content.

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

Add the following configurations.

				
					# 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/web1.example.com;
client_max_body_size 256M;
index info.php;
server_name web1.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/php8.1-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 done.

Some of the above directives are explained below:

  • fastcgi_cache_path: Define FastCGI cache and its storage location, memory zone, and the key for cache lookup.
  • add_header: Validate the FastCGI cache.
  • fastcgi: Defines the path of the php-fpm socket.
  • fastcgi_cache: Used to enable caching.
  • fastcgi_cache_valid: Setup the cache time with status code 200, 301, 302 will be cached for 60 minutes.
  • fastcgi_cache_lock: Allows only the first request through the upstream PHP-FPM server.

Then, verify the Nginx configuration file for any syntax error using the following command.

				
					nginx -t
				
			

If the Nginx configuration is fine, you will see the following output.

				
					nginx: the configuration file /etc/nginx/nginx.conf syntax is ok
nginx: configuration file /etc/nginx/nginx.conf test is successful
				
			

Next, activate the Nginx virtual host using the following command.

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

Finally, reload the Nginx service to apply the changes.

				
					systemctl restart nginx
				
			

Verify Nginx Caching

At this point, Nginx is configured to serve static content. Now, it’s time to test whether caching works or not.

First, open your command line interface and access your Nginx server using the curl command.

				
					curl -I http://web1.example.com
				
			

The first time, you will receive the “X-Content-Status: MISS” as shown in the below screen.

Now, open your web browser and access your Nginx web server using the URL http://web1.example.com. You should see the PHP test page.

Then, refresh the page 4 to 5 times then run the following command again to test the caching

				
					curl -I http://web1.example.com
				
			

This time, you will receive the “X-Content-Status: HIT” as shown below.

The above screenshot indicates that Nginx is now caching the content properly.

You can also check the Nginx cache directory using the following command.

				
					ls /etc/nginx/cache/
				
			

This will shows you the cache in the following output.

				
					4 e
				
			

Nginx Caching: How to Use Nginx for Caching Static Content Conclusion

In this guide, we installed Nginx and test the default caching. Then, we configured Nginx to serve static content and test it via the curl command. You can now implement caching in the production environment to speed up your website loading time.

Caching has various advantages, such as improving application performance, reducing latency, database cost, and more. Caching can even lessen the pressure on your database and shield it from worse performance or even from crashing during spikes by diverting a large portion of the read load from the backend database towards the in-memory layer.

Avatar for Hitesh Jethva
Hitesh Jethva

I am a fan of open source technology and have more than 10 years of experience working with Linux and Open Source technologies. I am one of the Linux technical writers for Cloud Infrastructure Services.

0 0 votes
Article Rating
Subscribe
Notify of
0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x