简体   繁体   中英

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 right 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');

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.

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");

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM