GET参数通过php未读取的.htaccess子域传递


GET parameter passed through an .htaccess subdomain not read by php

场景

我有以下代码:

test.php

<?php
if(empty($_GET['lang'])){
    $user_language = explode("-",$_SERVER['HTTP_ACCEPT_LANGUAGE']);
    $language = $user_language[0];
    header('Location: http://'.$language.'.localhost'.$_SERVER['REQUEST_URI']);
}
else{
    $lang = $_GET['lang'];
    $content = array("en"=>"This is a test.","it"=>"Questo è un test.");
    echo $content[$lang];
}
?>

.htaccess

RewriteEngine On
RewriteBase /
RewriteCond %{HTTP_HOST} ^'.localhost$ 
RewriteRule (.*) - [QSA,E=LANG:%1]
RewriteRule (.*) $1?lang=%{ENV:LANG} [QSA]

我的代码应该做什么

如果未定义$_GET['lang'],请从浏览器发送的标头中获取用户的语言,并将其重定向到与其语言对应的子域:子域应与$_GET['lang'']一致。

什么不起作用

通过访问localhost/test.php,我被重定向到正确的子域,但重定向无休止地循环。此外,如果我访问en.localhost/test.php,并且我的语言是意大利语,我会在循环之前重定向到它.localhost/trest.php。

我的问题

我该如何解决这个问题?

您可以使用:

RewriteEngine On
RewriteBase /
RewriteCond %{HTTP:Accept-Language} ^([a-z]{2}) [NC]
RewriteRule ^ - [E=LANG:%1]
RewriteCond %{QUERY_STRING} !(?:^|&)lang= [NC]
RewriteCond %{HTTP_HOST} ^(?:[^.]+'.)?(localhost)$
RewriteRule (.*) http://%{ENV:LANG}.%1/$1?lang=%{ENV:LANG} [QSA,L,R=302]

Test.php:

<?php
    $lang = $_GET['lang'];
    $content = array("en"=>"This is a test.","it"=>"Questo è un test.");
    echo $content[$lang];
?>