How To Create A Custom Cache Server Using Nginx

Posted By : Ankit Gupta | 20-Apr-2020

Discover how to create a custom cache server using Nginx. If you think this CDN will be as good as the globally accessible CDN like Amazon AWS, then Cloudflare will not be sorry, as this is a single server spread globally across multiple locations.

 

What Is a CDN?

A Content Delivery Network (CDN) is a distributed portal (network) system that provides a user with pages and web content based on the user's geographic location, web page origin, and CDN domain. The aim is to provide high availability and productivity by distributing the service relative to the end spatially.

 

Will This CDN Be Fast Enough?

If you think this CDN will be as good as the globally accessible CDN like Amazon AWS, then Cloudflare will not work as this is a single server spread globally across multiple locations.

 

This would certainly be quicker than the usual current procedure, though, because the request will be pushed into a different URL and can be handled independently by the server. Even if the code is running in the same folder, the website will speed up.

 

Note: The creation of a separate CDN server or installation on the same server is the same operation. In case of heavy load, it will be a little faster in case of another CDN application.

 

Step 1 – Install Nginx:

sudo apt-get update
sudo apt-get install nginx

Step 2 – Configure your domain, using proxy pass to fetch the images on real time and store them.

sudo vim /etc/nginx/sites-available/cdn.example.com

Step 3 – Write the text below in the file

server {
  listen       80;
  server_name  cdn.yourdomain.com;

  location ~* .(gif|jpg|jpeg|png|avi|mpg|mpeg|mp4|htm|html|js|css|mp3|ico|flv)$ {
    expires max;
    proxy_set_header  X-Real-IP  $remote_addr;
    proxy_pass http://www.yourdomain.com;
    proxy_ignore_headers X-Accel-Expires Expires Cache-Control;
    proxy_store /var/www/cache$uri;
    proxy_store_access user:rw group:rw all:r;
  }
}

step 4 : Ctrl+X to save the file
step 5 :give write access to the cache folder

sudo chmod 777 /var/www/cache

step 6: create symlink to live server

ln -sf /etc/nginx/sites-available/cdn.yourdomain.com /etc/nginx/sites-enabled/

step 7: Restart nginx

sudo service nginx restart

Now the CDN is enabled, All static resources will now be forwarded to this folder. It will be a little slow for the first time but it will be faster after words as nginx downloads the file from your primary server and caches the file into its own cache directory.

About Author

Author Image
Ankit Gupta

Ankit is a Redhat Certified System Administrator and Redhat Certified Engineer. He is interested in learning new DevOps tools . He likes Linux, DevOps , Automation & Cloud Computing. He always try to complete the assigned tasks within in the given time.

Request for Proposal

Name is required

Comment is required

Sending message..