PHP 変数にあるサブドメインを照合してから$_SERVER['SERVER_NAME']
、内部リダイレクトを実行したいと考えています。Apache または nginx の書き換えはオプションではありません。これは、クライアント/ユーザーに表示される外部の書き換えであるためです。
私の正規表現は(.*(?<!^.))subdomain\.example\.com
、ご覧のとおり、サブドメイン (マルチレベル サブドメイン) 内のサブドメインに一致します。最初のキャプチャ グループは後で使用します。
これは私のPHPコードです:
if(preg_match('#(.*(?<!^.))subdomain\.example\.com#', $_SERVER['SERVER_NAME'], $match1)) {
echo $match1[1] . 'anothersubdomain.example.com';
}
ただし、サブドメインがたとえばcsssubdomain.example.com
、これは一致させたくない別のサブドメインであるため、これは失敗します。次の PHP スクリプトを使用して、一致をテストします。
$tests = array(
'subdomain.example.com' => 'anothersubdomain.example.com',
'css.subdomain.example.com' => 'css.anothersubdomain.example.com',
'csssubdomain.example.com' => 'csssubdomain.example.com',
'tsubdomain.example.com' => 'tsubdomain.example.com',
'multi.sub.subdomain.example.com' => 'multi.sub.anothersubdomain.example.com',
'.subdomain.example.com' => '.subdomain.example.com',
);
foreach( $tests as $test => $correct_answer) {
$result = preg_replace( '#(.*(?<!^.))subdomain\.example\.com#', '$1anothersubdomain.example.com', $test);
echo 'Input: ' . $test . "\n" .
'Expected: ' . $correct_answer . "\n" .
'Actual : ' .$result . "\n";
$passorfail = (strcmp( $result, $correct_answer) === 0 ? "PASS\n\n" : "FAIL\n\n");
echo $passorfail;
}
出力として得られます:
Input: subdomain.example.com
Expected: anothersubdomain.example.com
Actual : anothersubdomain.example.com
PASS
Input: css.subdomain.example.com
Expected: css.anothersubdomain.example.com
Actual : css.anothersubdomain.example.com
PASS
Input: csssubdomain.example.com
Expected: csssubdomain.example.com
Actual : cssanothersubdomain.example.com
FAIL
Input: tsubdomain.example.com
Expected: tsubdomain.example.com
Actual : tsubdomain.example.com
PASS
Input: multi.sub.subdomain.example.com
Expected: multi.sub.anothersubdomain.example.com
Actual : multi.sub.anothersubdomain.example.com
PASS
Input: .subdomain.example.com
Expected: .subdomain.example.com
Actual : .subdomain.example.com
PASS
奇妙なことは、一致するが一致csssubdomain.example.com
しないことtsubdomain.example.com
です。
この場合に使用できる正規表現を誰か知っていますか? 先読みと後読みのゼロ幅アサーションでいくつか試してみまし たが、実際には機能しませんでした。