Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Redirect all GET queries from one site to another

Tags:

url

php

get

Suppose I want to redirect all GET queries from one site to another, using PHP.
POST queries do not exist in the system.

For example, when the user connects to

www.mysite.com/index.php?action=myAction&pageno=2

I want him to be redirected to:

www.mySecondSite.com/index.php?action=myAction&pageno=2

I can get write a hard-coded code for each and every possible $_GET variable (myAction and pageno in my example), but it does not sound like a reasonable solution. Also, I've seen this solution which involves modifying the configuration of the Apache server. Suppose I can't change the server configuration.

For sure, there must be a way to get all of the variables and their values, and redirect it to another site.

like image 315
Andrey Rubshtein Avatar asked Dec 28 '22 05:12

Andrey Rubshtein


2 Answers

First of all you need to get complete URL, for example for my local server:

http://localhost/server_var.php?foo=bar&second=something

Try printing $_SERVER variable with print_r():

print_r( $_SERVER);

You should get result like this:

Array
(
    ...
    [REQUEST_URI] => /server_var.php?foo=bar&second=something
    ...
)

For more info take a look at manual page, so now you have your URL:

$url = 'http://www.mySecondSite.com' . $_SERVER['REQUEST_URI'];

And you can use header() to redirect your request:

header( 'Location: ' . $url);

I recommend taking look at HTTP status codes, 3xx ones, whether you want to use 302 Found (the default) or 307 Temporary Redirect...

The second special case is the "Location:" header. Not only does it send this header back to the browser, but it also returns a REDIRECT (302) status code to the browser unless the 201 or a 3xx status code has already been set.

So you can do this:

header('HTTP/1.0 307 Temporary Redirect');
header( 'Location: ' . $url);
like image 169
Vyktor Avatar answered Jan 05 '23 10:01

Vyktor


Write this php code at the top of the index.php page before your html tag.

<?
$newUrl = "www.mySecondSite.com/index.php";
if (!empty($_GET)){
$parameter = $_GET;
$firstTime = true;
foreach($parameter as $param => $value){
    if ($firstTime) {
        $newUrl .= "?" . $param . "=" . $value;
        $firstTime = false;
    } else {
        $newUrl .= "&" . $param . "=" . $value;
    }
}
}
header("Location: ".$newUrl);
/* Make sure that code below does not get executed when we redirect. */
exit;
?>
like image 21
Nantu Avatar answered Jan 05 '23 10:01

Nantu