GeoIP with Varnish¶
Using Varnish to handle GeoIP redirects is preferable to letting Magento handle this functionality. This also means that you no longer need extra Magento modules that tend to disable Varnish FPC on first load.
Compatibility¶
The default behavior is for Varnish to always redirect customers as per the rules you set up. This behavior is modified under certain conditions, so as not to break store switches, SEO, etc.
The visitor will not be redirected by Varnish under these conditions:
- The visitor has visited the domain before, as determined by
PHPSESSID
and a customalready_redirected
cookie. - The URL contains Magento query parameters, e.g.
___store=
or___from_store=
. - The URL contains the custom Magento URL path. This is done to ensure that you do not lock yourself out of your administration panel.
- The visitor's
User-Agent
is a bot, informed by Google etc official documentation. Google, for example, always crawls from the USA, and does not like being redirected.
How-to¶
The Varnish GeoIP VCL should be included in your Git repo for better reproducible builds. Staging and production sites will use the same rules.
The backend continually updates against a MaxMind GeoIP database. See also: MaxMind GeoIP country codes
In your local Git repo, create a directory called varnish
, containing a file called geoip.vcl
, and customize its content to match your staging and production domains.
## If any dev domain matches redirect between them
# Check if any of the prod domains match
if ( req.http.x-host == "my-prod-store.com" ||
req.http.x-host == "my-prod-store.dk" ||
req.http.x-host == "my-prod-store.fi" ) {
# Redirect to our default store if they are from the USA?
if ( req.http.x-host != "my-prod-store.com" && req.http.X-Country-Code == "US" ) {
return ( synth(750, "my-prod-store.com" ));
# Redirect to our Danish store if they are from the Denmark?
} elseif ( req.http.x-host != "my-prod-store.dk" && req.http.X-Country-Code == "DK" ) {
return ( synth(750, "my-prod-store.dk" ));
# Redirect to our Finnish store if they are from Finland?
} elseif ( req.http.x-host != "my-prod-store.fi" && req.http.X-Country-Code == "FI" ) {
return ( synth(750, "my-prod-store.fi" ));
}
}
# Or Check if any of the stage domains match
elseif ( req.http.x-host == "my-stage-site.com" ||
req.http.x-host == "dk.my-stage-site.com" ||
req.http.x-host == "fi.my-stage-site.com" ) {
# Redirect to our default store if they are from the USA?
if ( req.http.x-host != "my-stage-site.com" && req.http.X-Country-Code == "US" ) {
return ( synth(750, "my-stage-site.com" ));
# Redirect to our Danish store if they are from the Denmark?
} elseif ( req.http.x-host != "dk.my-stage-site.com" && req.http.X-Country-Code == "DK" ) {
return ( synth(750, "dk.my-stage-site.com" ));
# Redirect to our Finnish store if they are from Finland?
} elseif ( req.http.x-host != "fi.my-stage-site.com" && req.http.X-Country-Code == "FI" ) {
return ( synth(750, "fi.my-stage-site.com" ));
}
}