PHP redirect based on HTTP_HOST/SERVER_NAME within same domain
I am trying to redirect to a specific path based on HTTP_HOST or SERVER_NAME with a PHP-script.
I have 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 redirection error.
Ok, this 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 appears I need the REQUEST_URI field, otherwise it wouldn't work.
The most common redirection error is a redirection loop.
- Does the script really end after your first example?
- Where does $host come from?
Also, SERVER_NAME is usually an apache configured global name, HTTP_HOST is really the right way to do this.
HTTP_HOST may contain the port number, keep this in mind.
So what's the url of your script, and where are you redirecting to?
A simple way to debug is to echo the contents of HTTP_HOST and instead of calling header(), also call 'echo'.
Because your are redirecting to the same server (example.dk) and your code executes 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");
}
精彩评论