假设我有以下网址:
http://example.com/index.php?user/1234
我想要 PHP 查询做的是将用户重定向到以下 URL:
http://example.com/test/index.php?user/1234
当然,URL 不仅应该重定向
?user/1234
,还应该重定向 ?anything/343
。我想保持 url 不变,只添加 /test/
,后面的部分保持不变。
我该如何做到这一点?我能找到的只是一般重定向,而不是特定于 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 Gogolek 的答案,使其对我有用。这就是我的问题的解决方案:
$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);
这曾经很麻烦,但现在对我有用:
header("Location: /test/index.php?" .$_SERVER['QUERY_STRING']);
应该是一个简单的标头重定向
header("Location:http://example.com/test/index.php?user/1234");
如果重定位依赖于查询,那么你需要构建位置url。
例如,如果您想在页面上使用 2 个变量,其中 1 个为
$page
,1 个为 $id
,您可以这样做。
$id = 123;
$page = 'user';
header("Location:http://example.com/test/index.php?".$page."/".$id);
这会产生一个 url
http://example.com/test/index.php?user/123