Magento 2 - Geo IP Redirect and Varnish
Okay seems like I got it working after struggling. In our case we always redirect the first visitor to the correct store. Redirect directly from Varnish. No bypassing.
It is super messy but if anyone got a better solution feel free to post it here.
Install Varnish GeoIP Module
https://rageagainstshell.com/2016/05/geoip-location-in-varnish/
Make sure to clone the correct branch (regarding your Varnish version)
otherwise it won't work. In my case it was:
git clone https://github.com/varnish/libvmod-geoip --branch=4.1
Add this at the beginning of your varnish file. (Most likely under /etc/varnish/default.vcl) add
import geoip;
Inside the sub vcl_recv section add something like this:
if (req.http.Cookie !~ "PHPSESSID=") {
set req.http.X-Country-Code = geoip.country_code(req.http.X-Forwarded-For);
if(req.url !~ "/(pub/)?(media|static)/") {
if (req.url !~ "/de/" && req.http.X-Country-Code == "DE") {
set req.http.subshop = "/de/";
return (synth(750, "Redirect"));
} elseif (req.url !~ "/us/" && req.http.X-Country-Code ~ "(US|MX|CA)") {
set req.http.subshop ="/us/";
return (synth(750, "Redirect"));
}
}
}
If there is a session already -> Nevermind
Otherwise check if the request is not a static file
Then check if user is already in the correct store. Otherwise set variable for later use (see below)
Return synth error.
At the bottom of your default.vcl file add this to do the redirect:
sub vcl_synth {
if (resp.status == 750) {
if(req.url != resp.http.Location) {
set resp.status = 301;
set resp.http.Location = req.http.subshop + regsuball(req.url, "^(/de/|/us/|)","")
}
return (deliver);
}
}
First prevent redirect loops. Set redirect response status Strip store_view_codes from url and replace it with the correct one.