2012-06-25 81 views
2

我想如果我的访问者去subdomain.example.com,他们会被重定向到anothersubdomain.example.com。如果他们去css.subdomain.example.com他们重定向到css.anothersubdomain.example.com正确地重定向访问者(PHP和正则表达式)

我试过以下的正则表达式(用的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他们也重定向也t ○: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重写。

在此先感谢。

回答

3

worked for me

$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"; 
} 

你会得到as output

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/'); 
} 
+1

+1 。我称之为TDA - “测试驱动的答案”。 ) – raina77ow

+1

谢谢你完美的作品!我的名誉太小,否则+1 – user1480019

+1

@nickb只有一件事情是关于带有连字符的子域(css-test.example.com)?和一个双点(subdomain.subdomain.example.com)子域? – user1480019

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

[这将失败](http://codepad.viper-7.com/ECx33k)如果有一个子域的后缀是“子域”。 – nickb