Search code examples
apache.htaccesshttp-redirectgeolocationcloudflare

.htaccess Redirect with Cloudflare location


I'm really struggling to place redirects into my .htaccess file based on the cloud flare country code. I'm either getting "too many redirect errors" or 500 internal errors using examples from across this site.

I currently have this:

Options +FollowSymLinks
RewriteEngine on

SetEnvIf CF-IPCountry "(.*)$" Country=$1

RewriteCond %{ENV:Country} GB
RewriteRule ^(.*)$ http://example.com/$1 [R,L]

So I need the default domain to be http://example.com

but if a country code of GB comes from cloudflare for example, I need it to redirect to:

http://example.com/gb

With my limited knowledge of .htaccess is this possible?


Solution

  • Try with:

    Options +FollowSymLinks
    RewriteEngine on
    
    RewriteCond %{HTTP:CF-IPCountry} ^GB$
    RewriteCond %{REQUEST_URI} !(?:gif|png|jpg|jpeg|css)$ [NC]
    RewriteRule !^gb/ /gb%{REQUEST_URI} [NC,NE,R,L]
    

    Redirect http://example.com/test to http://example.com/gb/test when the request comes from a user with CF-IPCountry=GB which is not already using a link with /gb/