為了 SEO 與權重集中,需將非 www 網域、index.php 首頁等非標準 URL 以 301 Moved Permanently 導向規範格式。本文提供可直接部署的 301.php,於入口檔 index.php 最頂端 require_once 引入即可生效。
<?php
// 301.php — 放置於專案根目錄,於 index.php 第一行 require_once '301.php';
$targetDomain = 'www.example.com'; // 目標規範網域(請修改為您的正式網域)
$currentHost = $_SERVER['HTTP_HOST'];
$requestUri = isset($_SERVER['REQUEST_URI']) ? $_SERVER['REQUEST_URI'] : '';
$requestUri = strtolower($requestUri);
// 首頁去除 index.php
if ($requestUri === '/index.php') {
$requestUri = '';
}
// 若當前 Host 不等於目標網域,發送 301 導向
if ($currentHost !== $targetDomain) {
// 重要:先發送狀態碼,再發送 Location
header('HTTP/1.1 301 Moved Permanently', true, 301);
header('Location: https://' . $targetDomain . $requestUri);
exit; // 必須 exit,避免後續程式繼續執行
}
// 可選:強制 HTTPS(若尚未由 Web Server 處理)
if (empty($_SERVER['HTTPS']) || $_SERVER['HTTPS'] === 'off') {
header('HTTP/1.1 301 Moved Permanently', true, 301);
header('Location: https://' . $targetDomain . $requestUri);
exit;
}
?>
| 步驟 | 程式碼 | 說明 |
|---|---|---|
| 1. 取得請求資訊 | $_SERVER['HTTP_HOST'], $_SERVER['REQUEST_URI'] | 含查詢字串,不含協定與網域 |
| 2. 規範化 URI | strtolower(), 去除 /index.php | 避免大小寫差異導致重複收錄 |
| 3. 判斷是否需導向 | $currentHost !== $targetDomain | 同時處理非 www、舊網域、IP 直接存取等情況 |
| 4. 發送 301 標頭 | header('HTTP/1.1 301...', true, 301) | 第 2 參數 true 替換既有同類標頭,第 3 參數強制狀態碼 |
| 5. 立即結束 | exit | 防止後續輸出導致「Headers already sent」 |
# 檢查 301 狀態碼與 Location curl -I https://example.com/index.php curl -I https://example.com/ curl -I https://example.com/page # 預期輸出 HTTP/1.1 301 Moved Permanently Location: https://www.example.com/
正確實作 301 導向,能有效整合連結權重、避免重複內容收錄,是 SEO 技術優化的基礎動作之一。