0

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.

Ralph
  • 418
  • 8
  • 18

1 Answers1

1

I figured this out. The solution was to not redirect visits from the country after they've been redirected to the country's sub-folder. I'll explain.

The following rule redirects users to example.com/us

# US
RewriteCond %{ENV:GEOIP_COUNTRY_CODE} ^US$
RewriteRule ^(.*)$ https://example.com/us$1 [L]

Once this redirection has happened, you should not re-use this rule in the .htaccess file in the us sub folder or it will result in a redirect loop. You can include rules for other countries to force them back to their country's sub folder, but do not include redirect rules for that country in it's sub folder (the US in this case).

/var/www/example.com/.htaccess

# 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]

/var/www/example.com/us/.htaccess

# UK
RewriteCond %{ENV:GEOIP_COUNTRY_CODE} ^UK$
RewriteRule ^(.*)$ https://example.com/uk$1 [L]

I hope this helps!

Ralph
  • 418
  • 8
  • 18