Auto Currency Switcher Based On Country Code With Varnish
- Bilal Malik
- Aug 10, 2019
- 1 min read
I faced the issue like “auto currency switcher is not working after installing varnish, it displayed the firstly loaded cached content to all the locations”. The solution is we need to add country code as a vary header so each country region has separate cached content. e.g) India has separate cached content of the home page, USA has separate cached content of home page similarly each country has a different type of cached contents.
We assume you already configured the varnish in Magento 2. Please follow the below steps to get and set country code in the varnish configuration file. We need to install GeoIP vmod to get country code
GeoIP vmod installation:
apt-get update
apt-get install git-core libgeoip-dev apt-transport-https libtool python-docutils automake make
apt-get install -y pkg-config libvarnishapi1 libvarnishapi-dev autotools-dev
cd /usr/src/
git clone -b 4.1 https://github.com/varnish/libvmod-geoip
cd libvmod-geoip
./autogen.sh
./configure
make
make install
cd /usr/share/GeoIP/
mv GeoIP.dat GeoIP.dat.old
wget -O GeoIP.dat.gz http://geolite.maxmind.com/download/geoip/database/GeoLiteCountry/GeoIP.dat.gz
gunzip GeoIP.dat.gz
Varnish configuration: Need to add the below line in /etc/varnish/default.vcl
import geoip;
sub vcl_recv {
unset req.http.X-Country-Code;
set req.http.X-Country-Code = geoip.country_code(req.http.X-Forwarded-For);
}
Magento code change: You need to find the place of set currency code execution block in PHP and retrieve the currency code from vary header and set it as currency code.
header('Vary: X-Country-Code');
$countryCode = $_SERVER['HTTP_X_COUNTRY_CODE'];
I hope it helps.
Comments