带有查询参数的PHP重定向

带有查询参数的PHP重定向,php,url-redirection,Php,Url Redirection,假设我有以下URL: http://example.com/index.php?user/1234 http://example.com/test/index.php?user/1234 我希望PHP查询将用户重定向到以下URL: http://example.com/index.php?user/1234 http://example.com/test/index.php?user/1234 当然,URL不仅应该重定向?user/1234,还应该重定向?anything/343。我想保

假设我有以下URL:

http://example.com/index.php?user/1234
http://example.com/test/index.php?user/1234
我希望PHP查询将用户重定向到以下URL:

http://example.com/index.php?user/1234
http://example.com/test/index.php?user/1234
当然,URL不仅应该重定向
?user/1234
,还应该重定向
?anything/343
。我想保持url不变,只向其中添加
/test/
,之后的部分保持不变


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

应该是一个简单的标题重定向

header("Location:http://example.com/test/index.php?user/1234");
如果重新定位依赖于查询,则需要构建位置url

例如,如果您想在页面上使用两个变量,一个是
$page
,另一个是
$id
,您可以这样做

 $id = 123;
 $page = 'user';

 header("Location:http://example.com/test/index.php?".$page."/".$id);
这将生成一个

http://example.com/test/index.php?user/123

您可以使用PHP
标题('location:url')


URL是您预期的新目的地

如果我正确理解了您的问题,您需要解析您的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);

我修改了Kasia Gololek的答案,使之适合我。这就是我问题的答案:

$fullUrl = $_SERVER[REQUEST_URI];
// split the url
$url = parse_url($fullUrl);
$url['path'] = "/test" . $url['path'];
// create the new url with test in the path
$newUrl = $url['path']."?".$url['query'];
header("Location:" .$newUrl);


是的,但是如果URL没有“?user/1234”,而是“?help/343”,那么我该怎么办?然后您会将其更改为
标题(“位置:http://example.com/test/index.php?help/343");@OldMcDonald请更详细地说明您正在尝试执行的操作achieve@OldMcDonald不要静态编写,而是通过将URL放入变量来动态编写。顺便说一句,URL格式似乎真的很奇怪…我现在把我的帖子说得更清楚了。我想将
/test/
部分添加到URL中,之后所有内容都保持不变。我不知道新的目的地,它取决于查询。您能更具体一点吗?每次URL的
test
部分会有什么不同?不,
test
会保持不变。只有之后的零件才应更换。例如,
example.com/index.php?which
应该变成
example.com/test/index.php?which
您可以捕获它,并将它附加到新构建的URL中。Kasia Gogolek的回答解释得更多。是的,你理解得对。然而,代码并没有完全正确地工作。我得到
http://example.com/:///test_://example.com/index.phpuser/1234/
作为URL。所以它有一些错误的
`符号,它缺少了
?`字符,我得到了两次域名。我忘记了路径和查询之间的问号,除了它对我有用之外。奇怪的是,我得到了以下
http://example.com/:///test://example.com/index.php?user/1234
。因此,
://
有些奇怪,而且它没有删除第二个
example.com
您的:$\u服务器['REQUEST\u SCHEME']$\u服务器[HTTP\u主机]$\u服务器[REQUEST\u URI]的值是什么?好的,我修复了它。谢谢你的帮助。我在OP中发布了我的编辑。请不要在你的问题中添加答案。为什么不?对于我的原始案例,公认的答案并非100%正确。我应该把它贴在哪里?作为这个问题的实际答案,老麦克唐纳。谢谢。在堆栈溢出时,问题和答案是分开的:-)