You can try to check the visitor country via the geojs.io, and then build the logic for redirecting.
See the JS code below:
geoTargeting();
function geoTargeting() {
return new Promise((resolve, reject) => {
fetch('https://get.geojs.io/v1/ip/country.json').then(response => response.json()).then(data => {
const currentHostname = window.location.hostname;
const currentPath = window.location.pathname;
let newUrl;
if (data.country === 'US') { // Check if country US
const subdomain = 'us';
newUrl = window.location.protocol + '//' + subdomain + '.' + currentHostname + currentPath;
window.open(newUrl); // Redirect
} else {
resolve(false);
}
}).catch(error => {
console.error('Error:', error);
resolve(false);
});
});
}