gpt4 book ai didi

php - 正确重定向访问者(PHP 和 Regex)

转载 作者:行者123 更新时间:2023-12-04 05:41:40 26 4
gpt4 key购买 nike

我想如果我的访客去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 重写。

提前致谢。

最佳答案

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

关于php - 正确重定向访问者(PHP 和 Regex),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11190847/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com