Configure Varnish for Commerce or Magento
Configure Magento to use Varnish
To configure Magento to use Varnish:
- Log in to the Admin as an administrator.
- Click Stores > Settings > Configuration > Advanced > System > Full Page Cache.
- From the Caching Application list, click Varnish Caching.
- Enter a value in the TTL for public content field.
-
Expand Varnish Configuration and enter the following information:
Field Description Access list Enter the fully qualified hostname, IP address, or Classless Inter-Domain Routing (CIDR) notation IP address range for which to invalidate content.
Backend host Enter the fully qualified hostname or IP address and listen port of the Varnish backend or origin server; that is, the server providing the content Varnish will accelerate. Typically, this is your web server.
Backend port Origin server's listen port. Grace period The grace period determines how long Varnish serves stale content if the backend is not responsive. The default value is 300 seconds. - Click Save Config.
You can also activate Varnish from the command line–instead of logging in to the Admin—using the Magento command-line interface tool:
1
bin/magento config:set --scope=default --scope-code=0 system/full_page_cache/caching_application 2
Export a Varnish configuration file
To export a Varnish configuration file from the Admin panel:
-
Click one of the export buttons to create a
varnish.vcl
you can use with Varnish.For example, if you have Varnish 4, click Export VCL for Varnish 4
The following figure shows an example.
-
Back up your existing
default.vcl
. Then rename thevarnish.vcl
file you just exported todefault.vcl
. Then copy the file to the/etc/varnish/
. directory.1
cp /etc/varnish/default.vcl /etc/varnish/default.vcl.bak2
1
mv <download_directory>/varnish.vcl default.vcl
1
cp <download_directory>/default.vcl /etc/varnish/default.vcl
-
We recommend you open
default.vcl
and change the value ofacl purge
to the IP address of the Varnish host. (You can specify multiple hosts on separate lines or you can use CIDR notation as well.)For example,
1 2 3
acl purge { "localhost"; }
-
If you want to customize the Vagrant health checks or grace mode or saint mode configuration, see Advanced Varnish configuration.
-
Restart Varnish and your web server:
1
service varnish restart
1
service httpd restart
Cache Static Files
Static files should not be cached by default, but if you want to cache them, you can edit the section Static files caching
in the VCL to have the following content:
1
2
3
4
5
6
7
# Static files should not be cached by default
return (pass);
# But if you use a few locales and don't use CDN you can enable caching static files by commenting previous line (#return (pass);) and uncommenting next 3 lines
#unset req.http.Https;
#unset req.http./* */;
#unset req.http.Cookie;
You need to make these changes before you configure Magento to use Varnish.
Related topics
- Advanced Varnish configuration (Optional)
- Final verification