How to Setup NGINX as a Caching Reverse Proxy


setup nginx as a caching reverse proxy

NGINX is a great reverse proxy that can be used in front of Apache/Django. It can not not only proxy requests to several back end servers but also do load balancing. In fact, it can also cache the generated pages and serve subsequent requests from the cached pages. This will not only reduce server load but also improve website speed. In this case, NGINX will act as a caching reverse proxy. Let us take a look at how to setup NGINX as a caching reverse proxy.

 

How to Setup NGINX as a Caching Reverse Proxy

Here are the steps to setup NGINX as a caching reverse proxy.

 

1. Open NGINX config file

Open NGINX config file in a text editor.

You will find it at one of the following locations, depending on the type of installation


/etc/nginx/conf.d/default.conf
/etc/nginx/sites-enabled/default
/etc/nginx/nginx.conf

 


$ sudo vim /etc/nginx/nginx.conf

 

2. Setup NGINX as a Caching Reverse Proxy

Let’s say you want to NGINX cache items for 60 minutes, and proxy the ones that can’t be cached to example.com backend servers.

http {
  proxy_cache_path  /var/www/cache levels=1:2 keys_zone=my-cache:8m max_size=1000m inactive=600m;
  proxy_temp_path /var/www/cache/tmp; 


  server {
    location / {
      proxy_pass http://example.net;
      proxy_cache my-cache;
      proxy_cache_valid  200 302  60m;
      proxy_cache_valid  404      1m;
    }
  }
}

You can use the proxy_cache_valid to explicitly set the cache expiry for each type of response.

 

3. Reload NGINX web server

Test the config file to ensure there are no errors.

$ sudo nginx -t

 

If you get no error message, reload NGINX server to apply changes.

$ sudo service nginx reload

 

That’s it! NGINX will now automatically proxy requests to back end servers, cache generated pages if possible, and serve subsequent requests from cache.

 

About Sreeram Sreenivasan

Sreeram Sreenivasan is the Founder of Ubiq, a business dashboard & reporting platform for small & medium businesses. Ubiq makes it easy to build business dashboards & reports for your business. Try it for free today!