[英]Cant redirect using php's header function
我有一個很奇怪的問題。 我正在網站上進行大量重定向,並希望將“ / old_url”和“ /old_url.html”重定向到“ / new_url”。 一切都可以與'/ old_url'一起正常工作,但是'/old_url.html'總是返回404。在檢查了響應頭之后,我可以看到我的重定向在那里列出,但是它根本沒有重定向。 這是我的代碼
if($query && !headers_sent()){
header('Location: ' . $query[0]['new_url'], true, (int)$query[0]['status_code']);
exit;
}
如您所見,這里有一個位置標頭。 有人知道為什么它不起作用嗎?
我認為如果HTTP狀態為404,瀏覽器將不會遵循Location標頭。請在響應中發送301狀態代碼,您應該可以
您的回復應如下所示:
HTTP/1.1 301 Moved Permanently
Location: {URL}
我也建議將重定向發送到絕對網址
更新
看看這個: http : //php.net/http-response-code
/old_url
是將導致讀取index.php / index.htm
的路徑。
/old_url.html
是一個文件,它嘗試讀取文件本身,而不是任何PHP腳本。
您可能想要使用htaccess之類的東西進行重定向。
很奇怪..此代碼無法正常工作。
header('Location: ' . $query[0]['new_url'], true, (int)$query[0]['status_code']);
exit;
但這是可行的。
switch($query[0]['status_code']){
case 301:
header("HTTP/1.1 301 Moved Permanently");
header("Location: " . $query[0]['new_url']);
exit;
break;
case 302:
header("HTTP/1.1 302 Moved Temporarily");
header("Location: " . $query[0]['new_url']);
exit;
break;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.