2011-04-21 81 views
7

這是一個正確的URI爲header('Location: '),特別是./PHP 301重定向位置URI格式

header ('HTTP/1.1 301 Moved Permanently'); 
header ('Location: ./'); 

謝謝。

+1

你是否試圖添加一個尾部的斜槓到URL?有更好的方法來做到這一點。 – 2011-04-21 09:25:15

+0

我正在嘗試從包含該代碼的文件永久性地重定向到默認文件(index.something),該文件包含在與執行重定向的初始文件相同的文件夾中。 – Francisc 2011-04-21 09:36:10

+2

你應該使用絕對URI。請參閱:http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.30 – Treffynnon 2011-04-21 09:36:37

回答

5

您必須使用absolute URI according to the spec所以有點像以下應該爲你工作:

// check if the server is secure or not to determine URL prefix 
if(isset($_SERVER['HTTPS']) and 'on' === $_SERVER['HTTPS']) { 
    $location = 'https://'; 
} else { 
    $location = 'http://'; 
} 

// get the servers base URL 
$location .= $_SERVER['SERVER_NAME'] . '/'; 

// grab the current URI without a file name in it 
$location .= dirname($_SERVER['REQUEST_URI']) . '/'; 

header('Location: ' . $location); 
exit(); 
+0

謝謝,Treffynnon。 – Francisc 2011-04-21 10:03:59

7

您還可以使用:

header('Location: /', false, 301); 

我假設你想重定向到「首頁」,那會是/不是./

+0

嗨,我想重定向到包含該代碼的文件所在的文件夾的根目錄。在這種特殊情況下,它也是網站的根源。我很擔心,因爲我讀了HTTP/1.1需要絕對路徑。 – Francisc 2011-04-21 09:35:22

+2

根據標準,絕對URL是必需的。這將工作,但無效 – 2011-04-21 09:36:52

+2

由於@Pekka提到見http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.30 – Treffynnon 2011-04-21 09:38:21