Implementing Varnish on Magento 2

Magento 2 comes with native Varnish support, so it is not necessary to install any supporting dependencies like on Magento 1. You just need to add the respective configuration to the Nginx configuration files.

There are three parts to enabling Varnish on a Magento 2 site,

  1. Change the admin setting for cache store
  2. Setting a cache host in app/etc/env.php
  3. Enabling Varnish in the Nginx configuration

When reading the following guide, replace example.com with your respective domain.

Store Configuration

  1. Log into your Magento admin as normal and go to Stores > Config > Advanced > System > Full Page Cache
  2. Change the caching application setting to "Varnish Cache", or if using MageRun,

    mr_examplecom config:store:set 'system/full_page_cache/caching_application' 2
  3. Save configuration
  4. Update the store configuration define the cache host, either

    • Open app/etc/env.php and manually add the following,

      'http_cache_hosts' =>
      array (
        0 =>
        array (
          'host' => 'lb1.i',
          'port' => '80',
        ),
      ),
    • Or, Execute the following command to automatically update the configuration file.

      php-7.0 bin/magento setup:config:set --http-cache-hosts=lb1.i:80
  5. Refresh the store configuration cache

Nginx Configuration

After updating the store configuration, you need to enable Varnish via Nginx. Add the following rules below, followed by an Nginx reload

Dynamic Content

In ___general/example.com.conf add

# Enable If-Modified-Since
set $magestack_last_modified true;

# Enable Varnish
set $magestack_cacheable true;

# The cache lifetime is not set when using Magento 2
# set $magestack_cache_lifetime 7d;

Semi-Static Content

In ___general/example.com.location.semi-static.conf

# Enable If-Modified-Since
set $magestack_last_modified true;

# Enable Varnish
set $magestack_cacheable true;
set $magestack_cache_lifetime 7d;

if (-f $request_filename) {
  set $magestack_clear_cookies true;
}

Static Content

In ___general/example.com.location.static.conf

# Enable If-Modified-Since
set $magestack_last_modified true;

# Enable Varnish (not recommended for static content unless using MageStack Edge or multiple web servers)
set $magestack_cacheable false;
set $magestack_cache_lifetime 7d;

if (-f $request_filename) {
  set $magestack_clear_cookies true;
}