The Ultimate Guide to Setting Up Nginx Reverse Proxy Cache

This article will walk you through the process step-by-step, provide real-life examples, and explain how to configure Nginx to bypass the cache based on specific conditions. Whether you’re new to Nginx or looking to optimize your current setup, this guide has everything you need.

What is a Reverse Proxy Cache?

A reverse proxy cache sits between your web server and clients, caching web content to reduce data transfer and server load. By serving cached content, it significantly improves website performance and speed.

Benefits of Using Nginx Reverse Proxy Cache

  1. Improved Performance: Serves cached content quickly, reducing server response time.
  2. Reduced Server Load: Decreases the number of direct requests to the web server.
  3. Bandwidth Savings: Lowers the amount of data transmitted between server and client.
  4. Enhanced Scalability: Handles more requests with the same server resources.

Installing Nginx

To begin, you need to have Nginx installed on your server. Below are the commands to install Nginx on Ubuntu and AlmaLinux.

Ubuntu

sudo apt-get update -y

sudo apt-get install nginx -y

AlmaLinux

sudo yum update -y

sudo yum install nginx -y

Configuring Nginx Reverse Proxy Cache

After installation, the next step is configuring Nginx. The configuration files are stored in the `/etc/nginx` directory. The main configuration file is `nginx.conf`.

Basic Configuration Example

Here’s a simplified example of an Nginx reverse proxy cache configuration:

http {

    proxy_cache_path /var/cache/nginx levels=1:2 keys_zone=PROXY-CACHE:10m inactive=60m;

    server {

        listen 80;
        server_name example.com;

        location / {

            proxy_pass http://backend_server;

            proxy_cache PROXY-CACHE;
            proxy_cache_valid 200 301 10s;
            proxy_cache_valid 302 404 30s;
            proxy_cache_methods GET HEAD;
            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_ignore_headers Set-Cookie Vary;

            real_ip_header X-Forwarded-For;
            proxy_set_header X-Real-IP $remote_addr;
            proxy_set_header X-Forwarded-Proto $scheme;
            proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
            proxy_set_header Accept-Encoding $encoding;
        }
    }
}

Explanation of Each Directive

  • proxy_cache_path: Defines the path and parameters for the cache storage. `levels=1:2` sets the directory structure, `keys_zone=PROXY-CACHE:10m` allocates 10MB of shared memory for the cache, and `inactive=60m` specifies that cached items inactive for 60 minutes will be removed.
  • proxy_pass: Specifies the backend server to which the requests should be forwarded.
  • proxy_cache: Activates caching for the specified location.
  • proxy_cache_valid: Sets the caching duration for different HTTP status codes.
  • proxy_cache_methods: Specifies the HTTP methods to be cached.
  • proxy_cache_use_stale: Allows serving stale cached content under certain conditions.
  • proxy_cache_background_update: Enables background updating of stale cache entries.
  • proxy_cache_lock: Ensures only one request at a time is sent to the backend server for the same resource.
  • proxy_ignore_headers: Ignores specific headers from the backend server.
  • real_ip_header and proxy_set_header directives: Ensure correct client IP address and other headers are passed to the backend server.

Advanced Configuration Options

Bypassing Cache with Cookies

You can configure Nginx to bypass the cache if a specific cookie is present. Here’s a snippet for this setup:

map $http_cookie $skip_cache {

    default 0;
    ~SESS 1;
    ~logged_in 1;

}
  • map $http_cookie $skip_cache {}: Creates a variable `$skip_cache` based on the presence of specific cookies (`SESS` or `logged_in`).

Modify your location block to bypass caching when `$skip_cache` is set:

location / {

    proxy_pass http://backend_server;

    proxy_cache_bypass $skip_cache;
    proxy_no_cache $skip_cache;

}

Bypassing Cache with URL Parameters

Similarly, you can bypass the cache based on URL parameters:

map $request_uri $skip_cache {

    default 0;
    ~*\/nocache 1;

}
  • map $request_uri $skip_cache {}: Creates a variable `$skip_cache` if the URL contains `/nocache`.

Modify your location block accordingly:

location / {

    proxy_pass http://backend_server;

    proxy_cache_bypass $skip_cache;
    proxy_no_cache $skip_cache;

}

Full Nginx Configuration Example

Below is the full Nginx configuration file incorporating all the features discussed:

http {

    proxy_cache_path /var/cache/nginx levels=1:2 keys_zone=PROXY-CACHE:10m inactive=60m;

    map $http_cookie $skip_cache {
        default 0;
        ~SESS 1;
        ~logged_in 1;
    }

    map $request_uri $skip_cache {
        default 0;
        ~*\/nocache 1;
    }

    server {

        listen 80;
        server_name example.com;

        location / {

            proxy_pass http://backend_server;

            proxy_cache PROXY-CACHE;
            proxy_cache_valid 200 301 10s;
            proxy_cache_valid 302 404 30s;
            proxy_cache_methods GET HEAD;
            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_ignore_headers Set-Cookie Vary;

            real_ip_header X-Forwarded-For;
            proxy_set_header X-Real-IP $remote_addr;
            proxy_set_header X-Forwarded-Proto $scheme;
            proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
            proxy_set_header Accept-Encoding $encoding;

            proxy_cache_bypass $skip_cache;
            proxy_no_cache $skip_cache;
        }
    }
}

Conclusion

Setting up an Nginx reverse proxy cache can drastically enhance the performance and scalability of your web applications. By following this guide, you’ll be able to configure a robust caching mechanism, bypass the cache under specific conditions, and understand the significance of each configuration directive.

Ready to take your web performance to the next level? Implement these configurations and see the difference today!

Elastic Hosting

Scalable hosting tailored to your website’s needs—no more frequent plan upgrades. With our elastic hosting, you only pay for the resources you actually use.

WordPress Hosting

Trusted by some of the worlds largest WooCommerce and WordPress sites, there’s a reason thousands of businesses are switching to G7