正确重定向访问者(PHP 和正则表达式)


Redirecting visitors correctly (PHP and Regex)

我希望如果我的访问者去subdomain.example.com他们被重定向到anothersubdomain.example.com。如果他们去css.subdomain.example.com,他们会被重定向到css.anothersubdomain.example.com等。

我尝试了以下正则表达式(带有preg_match):

尝试 1:

if(preg_match('#((['w'.-]+)'.subdomain|subdomain)'.example'.com#', $_SERVER['SERVER_NAME'], $match)) {
    header('Location: http://'.$match[1].'anothersubdomain.example.com/');
}

如果他们转到:subdomain.example.com他们将被重定向到:anothersubdomain.example.com

但是如果他们去: css.subdomain.example.com他们也会被重定向到: subdomain.example.com - 所以这是行不通

尝试 2:

if(preg_match('#(['w'.-]+)'.subdomain'.example'.com#', $_SERVER['SERVER_NAME'], $match)) {
    header('Location: http://'.$match[1].'.anothersubdomain.example.com/');
}

如果他们转到:css.subdomain.example.com他们将被重定向到:css.anothersubdomain.example.com

但是,如果他们转到:subdomain.example.com他们将被重定向到:.subdomain.example.com - 并且该 URL 无效,因此此尝试也不起作用。

有人有答案吗?我不想使用 nginx 或 apache 重写。

提前谢谢。

这对我有用:

$tests = array(
    'subdomain.example.com' => 'anothersubdomain.example.com',
    'css.subdomain.example.com' => 'css.anothersubdomain.example.com'
);
foreach( $tests as $test => $correct_answer) {
    $result = preg_replace( '#('w+'.)?subdomain'.example'.com#', '$1anothersubdomain.example.com', $test);
    if( strcmp( $result, $correct_answer) === 0) echo "PASS'n";
}

我所做的是使"第一个"子域的捕获组可选。因此,如果您打印出这样的结果:

foreach( $tests as $test => $correct_answer) {
        $result = preg_replace( '#('w+'.)?subdomain'.example'.com#', '$1anothersubdomain.example.com', $test);
    echo 'Input:    ' . $test . "'n" . 
         'Expected: ' . $correct_answer . "'n" . 
         'Actual  : ' .$result . "'n'n";
}

你会得到作为输出:

Input:    subdomain.example.com
Expected: anothersubdomain.example.com
Actual  : anothersubdomain.example.com
Input:    css.subdomain.example.com
Expected: css.anothersubdomain.example.com
Actual  : css.anothersubdomain.example.com

现在将其应用于您的需求:

if( preg_match( '#('w+'.)?subdomain'.example'.com#', $_SERVER['SERVER_NAME'], $matches)) {
    echo header( 'Location: http://'. (isset( $matches[1]) ? $matches[1] : '') .'anothersubdomain.example.com/');
}
if(preg_match('#('w*'.?)subdomain'.example'.com#', $_SERVER['SERVER_NAME'], $match)) {
    header('Location: http://'.$match[1].'anothersubdomain.example.com/');
}