Auto Currency Switcher Based On Country Code With Varnish

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.

5 views0 comments

Recent Posts

See All

Magento 2 CMS block with the same ID already exists

I have seen the below error when I open cms block grid something went wrong with processing the default view and we have restored the filter to its original state. I found the below log in the excepti

How to generate bearer token - Magento 2 REST API

We can generate the admin bearer token using the below command. Please run the below command in the terminal to generate a token. curl -XPOST -H 'Content-Type: application/json' http://www.domain.com/

Magento 2 script tag and available options in layout xml

We can add a script via layout XML file in Magento 2. The below format will stop the HTML parse until js downloaded and executed. <script src="Bilal_Usean/js/sample.min.js" /> The below format will st

Follow Me

  • LinkedIn
  • Twitter
  • Facebook
  • YouTube
  • Instagram

©2020 by Bilal Usean. Proudly created with Wix.com