Home > Software engineering >  Apache GeoIP redirect to page with question mark
Apache GeoIP redirect to page with question mark

Time:06-07

I have a stumbling block with GeoIP redirect (Apache/2.4.6 (CentOS))

.htaccess has the mandatory directives (necessary for functionality, change can break the whole site)

RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^ index.php [QSA,L]

so when I add to .htaccess a GeoIP rule like

RewriteCond "%{ENV:GEOIP_COUNTRY_CODE}" ^DE$
RewriteRule ^/?index\.php$ http://de.example.com/info.html$1 [L]

it works fine, but when I want to setup a similar redirect to a page with translation

RewriteCond "%{ENV:GEOIP_COUNTRY_CODE}" ^DE$
RewriteRule ^/?index\.php$ http://de.example.com/?lang=de$1 [L]

I have error "too many redirects".

Disable GeoIP in .htaccess and go directly to http://de.example.com/?lang=de - all OK.

Already spent few hours playing around syntax but still can't catch what's wrong, so thx for any idea to try !

CodePudding user response:

Most likely you don't want to do an external redirect that exposes your internal URL to clients. All you want (presumably) is to detect GEOIP country and based on that add a query parameter with same country code. You need to add a negated condition to stop rewrite when lang= query parameter is already present.

You may try this code in your .htaccess:

RewriteEngine On

RewriteCond "%{ENV:GEOIP_COUNTRY_CODE}" ^DE$
RewriteCond %{QUERY_STRING} !(^|&)lang= [NC]
RewriteRule ^/?(index\.php)?$ $0?lang=de [L,QSA]

RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^ index.php [L]

Make sure to clear your browser cache before testing this change.

  • Related