Website speed is no longer just a nice-to-have feature. It directly affects user experience, SEO rankings, and conversion rates. If your website struggles with traffic spikes or slow page loads, Varnish Cache can help improve performance.

Varnish is a high-performance HTTP accelerator designed to cache content and serve it quickly. By reducing the number of requests that reach your web server and backend applications, it can help lower server workload and improve response times.

In this guide, we’ll explain what Varnish Cache is, how it works, and how to install and configure it on an Ubuntu 22.04 server.

What Is Varnish Cache?

Varnish is a reverse proxy cache that sits in front of your web server, such as Apache or Nginx.

Instead of sending every visitor request directly to PHP, MySQL, or your content management system (CMS), Varnish stores frequently accessed pages in memory. When another visitor requests cached content, Varnish can serve it without requiring the backend server to generate the page again.

Why Is Varnish So Fast?

Varnish is designed to accelerate HTTP traffic through several key capabilities:

  • Uses RAM instead of disk: Frequently accessed content can be served from memory.
  • Optimized for HTTP traffic: It is built specifically to handle web requests efficiently.
  • Handles concurrent connections: It can manage thousands of simultaneous connections.
  • Reduces backend workload: It lowers CPU and database usage by serving cached responses.

How Varnish Works

The caching process is straightforward:

  1. A visitor requests a page.
  2. Varnish checks whether the requested page is already cached.
  3. If the content is cached, Varnish serves it immediately.
  4. If the content is not cached, Varnish forwards the request to the web server.
  5. The response is stored and reused for future requests.

This process reduces page generation time and helps your website handle more traffic efficiently.

When Should You Use Varnish?

Varnish works particularly well for websites that serve frequently requested content.

It is a good fit for:

  • Content-heavy websites
  • High-traffic blogs and news sites
  • CMS platforms such as WordPress, Drupal, and Magento
  • Websites with mostly anonymous visitors

However, Varnish is not ideal for every type of content. Highly personalized pages, admin dashboards, and logged-in user sessions may require careful configuration to avoid serving cached content incorrectly.

Installing Varnish Cache on Linux

For this tutorial, we’ll use an Ubuntu 22.04 server.

First, update your package list and install Varnish Cache.

Run the following commands:

apt update
apt install varnish -y

After installation, Varnish usually listens on port 6081 by default.

Now that Varnish is installed, let’s configure it to work with your web server.

Configuring Varnish with Your Web Server

Step 1: Change the Web Server Port

Varnish needs to receive incoming web traffic before forwarding requests to your backend web server.

To do this, move Apache or Nginx to a non-standard port, such as 8080.

For Apache, update the listening port to:

Listen 8080

Restart the web server after making the change.

Step 2: Set Varnish to Listen on Port 80

Next, edit the Varnish configuration file:

vi /etc/default/varnish

Update the listening port:

-a :80

Reload the systemd configuration and restart Varnish:

systemctl daemon-reload
systemctl restart varnish

Now, all incoming traffic flows through Varnish first.

Basic Varnish Configuration (VCL)

Varnish uses VCL (Varnish Configuration Language) to control caching behavior. With VCL, you can define which requests should be cached, which should bypass the cache, and how long content should remain stored.

Cache Only GET and HEAD Requests

The following example allows Varnish to cache GET and HEAD requests while passing other request methods directly to the backend:

sub vcl_recv {
  if (req.method != "GET" && req.method != "HEAD") {
      return (pass);
  }
}

Exclude Admin or Login Pages

Some pages contain sensitive or user-specific information and should bypass the cache.

For example, the following rule excludes WordPress admin and login pages:

if (req.url ~ "^/wp-admin" || req.url ~ "^/wp-login") {
    return (pass);
}

This ensures that dynamic or sensitive pages are not served from the cache.

Setting Cache Expiry (TTL)

You can control how long content stays in the cache by setting its Time to Live (TTL).

For example:

sub vcl_backend_response {
  set beresp.ttl = 5m;
}

This tells Varnish to keep the response in the cache for five minutes.

Handling Cookies Properly

Cookies can interfere with caching if they are not handled correctly. For static content, you can strip cookies to allow files to be cached more efficiently.

Use the following example:

if (req.url ~ "\.(css|js|png|jpg|jpeg|gif|svg)$") {
    unset req.http.cookie;
}

This allows static files such as CSS, JavaScript, and images to be cached without unnecessary cookie handling.

Testing If Varnish Is Working

After configuring Varnish, you’ll want to verify that it is receiving requests and serving cached content.

Check HTTP Headers

Run the following command:

curl -I http://yourdomain.com

Look for headers such as:

X-Varnish: 12345 67890

A cache HIT indicates that Varnish is serving the requested content from its cache.

Purging the Cache

When you update your website, you may need to clear cached pages so visitors receive the latest content.

You can configure a basic purge rule in VCL:

sub vcl_recv {
  if (req.method == "PURGE") {
      return (purge);
  }
}

Then, send a PURGE request to the page you want to clear:

curl -X PURGE http://yourdomain.com/page-url

This provides a way to remove cached content when updates need to appear immediately.

Varnish and CMS: Best Practices

If you’re using Varnish with a CMS such as WordPress, a few additional practices can help you get better results.

Use Varnish alongside PHP-FPM: Varnish can handle cached HTTP responses while PHP-FPM processes dynamic PHP requests that need to reach the application.

Pair with Redis or Memcached: These tools can provide object caching to complement Varnish’s page caching.

Exclude cart, checkout, and login pages: These pages often contain user-specific information and should not be served from a shared cache without careful configuration.

Monitor cache performance: Use varnishstat to monitor cache hit and miss ratios and understand how effectively Varnish is serving content.

Final Thoughts

Varnish Cache is a powerful tool for improving website performance without requiring changes to your application code. When configured correctly, it can reduce server workload, improve response times, and help your website handle traffic spikes more efficiently.

By understanding how caching works, configuring the right VCL rules, and monitoring cache performance, you can make better use of your server resources and deliver a faster browsing experience.

If website performance matters to your project, Varnish is worth considering as part of your hosting stack. With RackNerd VPS hosting, you have the flexibility to configure your server environment and deploy performance tools like Varnish Cache to support your website’s requirements.

How to Use Varnish Cache to Speed Up Your Website (Video Tutorial):

Server Hosting Solutions by RackNerd:

Shared Hosting
cPanel Web Hosting in US, Europe, and Asia datacenters
Logo
Reseller Hosting
Create your new income stream today with a reseller account
Logo
VPS (Virtual Private Server)
Fast and Affordable VPS services - Instantly Deployed
Logo
Dedicated Servers
Bare-metal servers, ideal for the performance-demanding use case.
Logo

Leave a comment

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