Redirect all GET requests from one site to another

Suppose I want to redirect all GET requests from one site to another using PHP .
POST on the system there are no requests.

For example, when a user connects to

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

I want it to be redirected to:

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

I can write hard code for every possible $_GET variable ( myAction and pageno in my example), but that doesn't seem like a reasonable solution. In addition, I saw this solution, which includes changing the configuration of the Apache server. Suppose you cannot change the server configuration.

Of course, there should be a way to get all the variables and their values ​​and redirect it to another site.

+4
source share
3 answers

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

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

Try printing the $_SERVER with print_r() :

 print_r( $_SERVER); 

You should get the result as follows:

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

Check out the man page for more information, so now you have your own url:

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

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

 header( 'Location: ' . $url); 

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

The second special case is the "Location:" header. Not only does this send this header back to the browser, but it will also return REDIRECT (302) for the browser if the status code 201 or 3xx is already set.

So you can do this:

 header('HTTP/1.0 307 Temporary Redirect'); header( 'Location: ' . $url); 
+4
source

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; ?> 
+4
source

Redirecting to .htaccess is a way, but if you say you cannot change this, you can insert a conditional header with code 301 in the index.php file: http://php.net/manual/en/function.header.php

You have the contents of a query string available in $_SERVER['QUERY_STRING']

+2
source

Source: https://habr.com/ru/post/1397272/


All Articles