301跳轉是指當用戶訪問某個URL時,服務器會將請求永久重定向到另一個URL,並返回狀態碼301。該方式常用於網站URL結構調整、頁面永久遷移,或者根據終端設備進行重定向。 PHP中實現301跳轉操作簡單,靈活且高效。
在PHP中,可以通過header()函數發送HTTP響應頭,將Location字段設置為目標URL,從而實現跳轉。
header("Location: https://www.example.com/new-url", true, 301);
exit;
上面代碼將訪問者重定向到指定的URL,並返回301狀態碼。第二個參數true表示替換之前相同名稱的header。
另一種方法是先調用http_response_code()設置狀態碼,再通過header()設置Location頭。
http_response_code(301);
header("Location: https://www.example.com/new-url");
exit;
這種寫法將狀態碼和跳轉地址分開處理,邏輯更加清晰。
以下示例展示了兩種實現301跳轉的完整代碼:
$url = "https://www.example.com/new-url";
// 方式一:header函數實現
header("Location: $url", true, 301);
exit;
// 方式二:http_response_code和header函數實現
http_response_code(301);
header("Location: $url");
exit;
調用header()之前,不能有任何頁面輸出,包括空格、換行或HTML標籤。否則會導致跳轉失敗或警告。
// 錯誤示例
echo "Hello World!";
header("Location: https://www.example.com");
exit;
// 正確示例
header("Location: https://www.example.com");
exit;
如果使用http_response_code()設置狀態碼,必須在調用header()設置Location頭之前完成。因為設置Location時,狀態碼會自動變為默認200。
// 錯誤示例
header("Location: https://www.example.com");
http_response_code(301);
exit;
// 正確示例
http_response_code(301);
header("Location: https://www.example.com");
exit;
PHP實現301跳轉操作簡單實用,無論是頁面URL調整還是跨終端重定向,都能輕鬆應對。只需正確使用header()和http_response_code()函數,並確保無提前輸出,即可保證跳轉穩定可靠。