我不相信这对于 .htaccess 是可能的。我有多个域:
domain.mx domain.com domain.ca
我想根据用户位置强制本地化 TLD。如果用户来自墨西哥,并访问domain.com/test/a/,他们将在第一次访问时被定向到domain.mx/test/a。从那里,网站将自动将用户保留在 .mx
这是我当前的 PHP 解决方案,但我不确定重写规则是否可能或更快:
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();
} Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号
基于:https:// serverfault.com/questions/357716/can-apache-conditionally-perform-a-rewrite-from-a-custom-http-header
RewriteCond %{HTTP:CF-IPCountry} = MX RewriteRule .* https://domain.mx%{REQUEST_URI} [R=301,L,QSA]文档:https://httpd.apache.org/docs /2.4/mod/mod_rewrite.html#rewritecond
但还要考虑到用户可能故意尝试访问与其位置不匹配的网站,例如:加拿大的西班牙语用户。我建议允许用户设置他们想要的区域设置,将该首选项存储在 cookie 中,并使用
%{HTTP_COOKIE}来控制重写行为。