I am trying to redirect users to a sub-folder based on their country and restrict access to another country's version of the site. I am using Apache's GeoIP module, the visitor's IP address and a maxmind database to determine the visitor's country.
I have a .htaccess
file in the root of example.com that contains:
# US
RewriteCond %{ENV:GEOIP_COUNTRY_CODE} ^US$
RewriteRule ^(.*)$ https://example.com/us$1 [L]
# UK
RewriteCond %{ENV:GEOIP_COUNTRY_CODE} ^UK$
RewriteRule ^(.*)$ https://example.com/uk$1 [L]
This works fine. Visitors from the US are redirected to the us sub folder and UK visitors are redirected accordingly. However, a US visitor can visit example.com/uk
directly and see the other country's version, I want to prevent this but my attempts have failed.
I duplicated the rewrite rules above into .htaccess
files in the sub folders and this resulted in a redirect loop when I visited example.com.
As a temporary solution, I am using the following which only allows access from the country approved to access the sub folder and sends a HTTP 403 for foreign visitors which works, but doesn't meet my requirements.
GeoIPEnable On
SetEnvIf GEOIP_COUNTRY_CODE US AllowCountry
SetEnvIf GEOIP_COUNTRY_CODE CA AllowCountry
Deny from all
Allow from env=AllowCountry
Any help is appreciated.