带有查询参数的 PHP 重定向

Old*_*ald 2 php url-redirection

假设我有以下网址:

http://example.com/index.php?user/1234
Run Code Online (Sandbox Code Playgroud)

我希望 PHP 查询做的是将用户重定向到以下 URL:

http://example.com/test/index.php?user/1234
Run Code Online (Sandbox Code Playgroud)

当然,URL 不仅要重定向?user/1234,还要重定向?anything/343。我想保持 url 不变,只添加 url /test/,然后保留相同的部分。

我如何做到这一点?我所能找到的只是一般重定向,而不是特定于 URL。谢谢。

Kas*_*lek 5

如果我正确理解您的问题,您需要解析您的 URL 字符串并将“test”添加到路径中。下面的代码应该做到这一点:

// $fullUrl = $_SERVER['REQUEST_SCHEME']."://".$_SERVER[HTTP_HOST].$_SERVER[REQUEST_URI];
$fullUrl = "http://example.com/index.php?user/1234";
// split the url
$url = parse_url($fullUrl);
$url['path'] = "/test" . $url['path'];
// create the new url with test in the path
$newUrl = $url['scheme'] . "://".$url['host'].$url['path']."?".$url['query'];
header("Location:" .$newUrl);
Run Code Online (Sandbox Code Playgroud)