Setup a CDN server
5 March, 2021 by
Setup a CDN server
Administrator

To tell you the truth, a CDN is just a web server and there is no magic to it. All I did was install Nginx on it.

Nginx is a webserver, just like Apache. The one important difference is that Nginx is very good with serving static content. I don’t need to have this machine do any processing, all I care is that it serves content. After receiving thousands of requests, my Apache web server simply died.

The motto is Nginx can serve 10,000 requests per second. I never had to serve that much content but it worked very well for me during spikes. So I set up nginx, moved all my assets to the server, and updated the DNS record. Now all my static files are served from cdn.idiallo.com. Very easy.

This works for me because I use a very primitive process for uploading my files, at least I used to (scp). If you are using a WordPress installation it will be complicated to customize the code to upload the files to a different server instead. But there is a simple solution.

Shared folders. If you are hosting with shared hosting providers you are out of luck. But for others, you can make your upload folder and shared folder, accessible from your CDN machine. This way you upload in one machine and it automatically reflects on the other.

Once your CDN is setup properly, you never have to touch it. All it does is serve files and update when you make new files available.

Installing Nginx

If you are using a debian machine all you need is this command:

sudo apt-get install nginx

Choose a folder where you want your asset folder to be: (/var/www/assets/). Then you can point Nginx to it. Create an Nginx config file:

vim /etc/nginx/sites-available/yourwebsite.com

And add these settings:

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

  location / {
    expires 90d;
    root /var/www/assets/;
  }
}

Also make sure you create a symlink in the sites-enabled folder.

That’s all there is to it. You can restart your server and start serving files from your own custom CDN now. You can update your DNS to use your new CDN.subdomain, which should be available in your hosting provider GUI.

Enjoy serving fast content without breaking your server.

Update:

If you want to upload files on your webserver but want to make them available on your CDN server, here is how you can share files between your webserver and CDN