将NGINX重写规则转换为PHP


Convert NGINX rewrite rule to PHP

我有这个NGINX重写URL:

if ($http_host !~ "([a-zA-Z0-9.-]+)'.example'.com(.+)") {
    rewrite  ^ http://example.com/browse.php?u=http://$1$2? permanent;
}

我想将规则转换为 PHP,因为我的主机不允许我将 NGINX 中的server_name更改为:*.example.com

我尝试过这样的事情:(此脚本位于索引中.php在我的域中,并且我已经打开了DNS通配符

<?php
function unparse_url($parsed_url) { 
    $scheme   = isset($parsed_url['scheme']) ? $parsed_url['scheme'] . '://' : ''; 
    $host     = isset($parsed_url['host']) ? $parsed_url['host'] : ''; 
    $port     = isset($parsed_url['port']) ? ':' . $parsed_url['port'] : ''; 
    $path     = isset($parsed_url['path']) ? $parsed_url['path'] : ''; 
    $query    = isset($parsed_url['query']) ? '?' . $parsed_url['query'] : ''; 
    $fragment = isset($parsed_url['fragment']) ? '#' . $parsed_url['fragment'] : ''; 
}
if(preg_match('/^([a-zA-Z0-9.-]+)'.example'.com'/(.+)$/', $_SERVER["SERVER_NAME"])){
    unparse_url(parse_url($_SERVER["SERVER_NAME"]));
    header('Location: $schemeexample.com/browse.php?u=$scheme$host$port$path$query$fragment');
}
else {
?>
<html>
**HTML CONTENT HERE**

如您所见,它使用 parse_url 解析 url 并将其从解析的 url 转换回字符串。

不幸的是,这个脚本不起作用,我将获取HTML页面的内容。有人有答案吗?

提前谢谢。

(功能unparse_url来自这里)

像这样的东西?

if(preg_match('#(['w'.-]+)'.example'.com(.+)#', $_SERVER['SERVER_NAME'].$_SERVER['REQUEST_URI'], $match)) {
    header('Location: http://example.com/browse.php?u=http://'.$match[1].$match[2]);
    die;
}