metinsaylan
metinsaylan
As an Amazon Associate, I earn from qualifying purchases.
  1. Home
  2. How To

Create a Personal CDN Server Using Nginx

Staff // (Updated: )

Nginx is an event-driven web server, that is why it is a perfect choice to create your own CDN server. You can then use this server to serve static assets on your website for example. In order to build your own CDN server, simply follow these steps:

Step1. Install Nginx on your hosting server.

yum install nginx

Step2. goto /etc/nginx/conf.d folder and back up all configuration files.

mkdir backups
mv *.conf backups

Step3. Create a new configuration file called pass.conf using your own favorite editor:

vim pass.conf

Step4. Put the following text into that file:

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

  location ~* .(gif|jpg|jpeg|png|wmv|avi|mpg|mpeg|mp4|htm|html|js|css|mp3|swf|ico|flv)$ {
    expires max;
    proxy_set_header  X-Real-IP  $remote_addr;
    proxy_pass http://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;
  }
}

Step5. Save Nginx configuration using :wq and quit.

Step6. Add Nginx to startup services.

chkconfig nginx on

Step7. Start Nginx.

service nginx start

For this configuration to work, you should create a cache folder under /var/www and it should have appropriate folder permissions for Nginx to work.

You should now forward all static resources to this server. If the file is not found, Nginx will download the file from your primary server and it will cache the file to its own cache directory.

Have fun.

5 Comments

  • Brian

    How would you use this for more than one domain?

  • nguyen

    Thanks so much but I would like to ask. My request was sent from the client to a master load balancer. If there is no resource to search, it will look at other CDN nodes before going to origin to get the static file. Thank you very much.

  • Tomas

    Hey Metin,

    nice article. I've tried to deploy this, however on every request the nginx cache keeps downloading the file from the origin even though the file is in the cache already. My origin is an apache2, serving simple static content.

    • Metin Şaylan

      Can you try with following settings; maybe it is a folder or permissions issue?

      <pre>
      proxy_pass http://yourdomain.com;
      proxy_ignore_headers X-Accel-Expires Expires Cache-Control;
      proxy_store on;
      proxy_temp_path /data/temp;
      proxy_store_access user:rw group:rw all:r;
      </pre>

Leave a Reply

Your email address will not be published.

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

More How To
Share Share Tweet