PHP redirection based on HTTP_HOST / SERVER_NAME within the same domain

I am trying to redirect to a specific path based on HTTP_HOST or SERVER_NAME using a PHP script.

I tried these scripts:

1.   

$domain = $_SERVER["SERVER_NAME"];
if (($domain == "example.dk") ||
   ($domain == "www.example.dk")) { 
   header("location: /index.php/da/forside"); 
}
?>

2.   

switch ($host) {

        case 'example.dk':
                header("HTTP/1.1 301 Moved Permanently");
                header("Location: http://www.example.dk/index.php/da/forside/");
                exit();

        case 'www.example.dk':
                header("HTTP/1.1 301 Moved Permanently");
                header("Location: http://www.example.dk/index.php/da/forside/");
                exit();



        default:
                header("Location: http://www.example.se");
                exit();

                }
?>

And other similar scripts. Either the page loads forever, or the browser returns some redirect error.

+5
source share
3 answers

Ok, here is how I solved it:

<?php
$domain = $_SERVER["SERVER_NAME"];
$requri = $_SERVER['REQUEST_URI'];
if (($domain == "www.example.dk" && $requri == "/index.php"  ||
   $domain == "example.dk") )  { 
   Header( "HTTP/1.1 301 Moved Permanently" ); 
   header("location: http://www.example.dk/index.php/da/forside"); 
}

else if (($domain == "uk.example.dk" && $requri == "/index.php"  ||
   $domain == "www.uk.example.dk") )  {
   Header( "HTTP/1.1 301 Moved Permanently" );    
   header("location: http://uk.example.dk/index.php/en/uk/home"); 
}

else if (($domain == "www.example.se" && $requri == "/index.php"  ||
   $domain == "example.se") )  { 
   Header( "HTTP/1.1 301 Moved Permanently" ); 
   header("location: http://example.se/index.php/sv/hem"); 
}

?>

It seems I need REQUEST_URI, otherwise it will not work.

+8
source

The most common redirect error is a redirect loop.

  • Does the script really end after the first example?
  • Where does $ host come from?

, SERVER_NAME , apache, HTTP_HOST - .

HTTP_HOST , .

, URL script ?

- HTTP_HOST header() "echo".

0

Since you are redirected to the same server (example.dk) and your code is executed again and again in a loop.

use this code instead:

$domain = $_SERVER["SERVER_NAME"];
if (($domain == "example.dk" ||
   $domain == "www.example.dk") && !$_GET['redirected'])  { 
   header("location: /index.php/da/forside?redirected=1"); 
}
0
source

All Articles