I don't believe this is possible with .htaccess. I have multiple domains:
domain.mx domain.com domain.ca
I want to force a localized TLD based on user location. If a user is from Mexico and visits domain.com/test/a/, they will be directed to domain.mx/test/a on their first visit. From there, the site will automatically keep the user in .mx
This is my current PHP solution, but I'm not sure if rewriting the rules is possible or faster:
add_action( 'template_redirect', 'my_callback' ); function my_callback() { $userCountry = $_SERVER["HTTP_CF_IPCOUNTRY"]; $baseurl = $_SERVER[HTTP_HOST]; $url = $_SERVER[REQUEST_URI]; // Mexico if (($userCountry == "MX") && (strpos($baseurl, 'mx') == false)) { $newurl = "https://domain.mx" . $url; wp_redirect( $newurl, 301 ); exit(); }
P粉4773692692024-01-11 14:45:43
RewriteCond %{HTTP:CF-IPCountry} = MX RewriteRule .* https://domain.mx%{REQUEST_URI} [R=301,L,QSA]
Documentation: https://httpd.apache.org/docs /2.4/mod/mod_rewrite.html#rewritecond
But also consider that users may deliberatelytry to access websites that do not match their location, for example: Spanish-speaking users in Canada. I recommend allowing the user to set the locale they want, storing that preference in a cookie, and using %{HTTP_COOKIE}
to control the override behavior.