开发者

PHP: 301 Redirect Page while maintaining GET variables

I have a page that has been replaced with a new page of a different name, is there a way to redirect this page while maintaining _GET variables passed in the url.

what I have righ开发者_开发百科t now:

old-page.php

header('Location: http://www.example.com/new-page.php', true, '301');

when users navigate to a url like old-page.php?var=1 they are taken to new-page.php , how can I get it to redirect them to new-page.php?var=1? the query string can be several different things, so I'd like a solution that can work w/ any combination of get variables.


header('Location: http://www.example.com/new-page.php'
   .(!empty($_SERVER['QUERY_STRING'])?'?'.$_SERVER['QUERY_STRING']:''),
   true, '301');


You can either use sessions:

session_start();
$_SESSION['your var'] = "value";

or you can pass it in your redirect url

header('Location: http://www.example.com/new-page.php?key=value', true, '301');


Can you do something like:

$parse = '';

foreach($_GET as $i => $j)
    $parse .= "$i=$j&";

$parse = (strlen($parse) > 0 ? "?" : "") . substr($parse, 0, -1);

header("Location: old-page.php$parse");


If you are using Apache, you can use the almighty mod_rewrite. This way, you can rewrite everything - GET, POST and more.

If you want to do it in PHP, in order to make it right(tm), you need to consider $_SERVER['HTTPS'], $_SERVER['HTTP_HOST'] and $_SERVER['SERVER_PORT'] as well. Just because when running HTTPS on a custom port, you maybe do not want to redirect to HTTP using default port.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜