Configuring Nginx Caching For Faster Performance

Hello Guys, today I am going to show you how to configure nginx cache for your server. Nginx cache helps website load faster, reduce server load, increases performance and more.

Why should you use NGINX CACHE?

  1. Increase Performance
  2. Reduce Server Load
  3. Save Resources
  4. Speed Up Pages
  5. And many more

Lets Go..
Caching with nginx is very easy just put bellow code in your nginx.conf file

proxy_cache_path /path/to/cache levels=1:2 keys_zone=my_cache:30m max_size=10g inactive=60m use_temp_path=off;

server {
    # ...
    location / {
        proxy_cache my_cache;
        proxy_pass 127.0.0.1:8000;
    }
}

Here /path/to/cache is the path which nginx will use to store the cached files, this directory should have write performance for nginx.

levels=1:2 meaning using more directories than a single directory. Because huge files in a single directory will slow down performance.

keys_zone is the name for your caching, here we are using my_cache. And 30m meaning the size for the cache index to be stored.

max_size is the maximum size of cache.

inactive=60m meaning that the cached resource will be deleted if not accessed within 60 minutes.

Also use

proxy_cache_path /path/to/cache levels=1:2 keys_zone=my_cache:30m max_size=10g inactive=60m use_temp_path=off;

server {
    # ...
    location / {
        proxy_cache my_cache;
        proxy_cache_revalidate on;
        proxy_cache_min_uses 1;
        proxy_cache_use_stale error timeout updating http_500 http_502
                              http_503 http_504;
        proxy_cache_background_update on;
        proxy_cache_lock on;
        proxy_pass 127.0.0.1:8000;
    }
}

proxy_cache_revalidate on; means that if the If-Modified-Since header exists the cache will be revalidated.
proxy_cache_min_uses 1; means that the resource will be cached after 1 hit.

proxy_cache_use_stale error timeout updating http_500 http_502
http_503 http_504;
is an important directive, the cached content will show in case of errors.

proxy_cache_background_update on; meaning the cache will be updated in background.

proxy_cache_lock on; will lock the user until to serve the cached content.

Everyone should use nginx cache because nowadays faster site is a must. Even Google urges to make your site faster. Faster website will definitely rank high on Google and other search engines. So make use of the powerful nginx cache.

Leave a Reply

Your email address will not be published. Required fields are marked *