核心代碼:最簡單的 301 重定向
<?php
// 必須在任何輸出之前
header('HTTP/1.1 301 Moved Permanently');
header('Location: https://www.example.com' . $_SERVER['REQUEST_URI']);
exit; // 關鍵:阻止後續代碼執行
完整可復用模組:301.inc.php
<?php
// 301.inc.php - 放在項目公共 include 目錄
// 配置目標主域名(不含協議)
$targetDomain = 'example.com';
// 可選:強制 HTTPS
$forceHttps = true;
// 獲取當前請求資訊
$currentHost = $_SERVER['HTTP_HOST'] ?? '';
$requestUri = $_SERVER['REQUEST_URI'] ?? '/';
$scheme = ($forceHttps || (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off')) ? 'https' : 'http';
// 判斷是否需要重定向
$needRedirect = false;
$targetUrl = '';
// 1. 強制 HTTPS
if ($forceHttps && $scheme === 'http') {
$needRedirect = true;
$targetUrl = 'https://' . $currentHost . $requestUri;
}
// 2. 統一主域名(去 www 或加 www)
$canonicalHost = 'www.' . $targetDomain; // 統一加 www
if ($currentHost !== $canonicalHost) {
$needRedirect = true;
$targetUrl = $scheme . '://' . $canonicalHost . $requestUri;
}
// 3. 執行重定向
if ($needRedirect) {
// 避免重定向循環
if (($scheme === 'https' && $currentHost === $canonicalHost) === false) {
header('HTTP/1.1 301 Moved Permanently');
header('Location: ' . $targetUrl);
exit;
}
}
在入口文件引入
<?php
// index.php 或公共 bootstrap.php 最頂部
require_once __DIR__ . '/includes/301.inc.php';
// 後續正常業務邏輯...
Nginx/Apache 層面實現(效能更高,推薦)
Nginx
server {
listen 80;
server_name example.com www.example.com;
# 強制 HTTPS
return 301 https://www.example.com$request_uri;
}
server {
listen 443 ssl http2;
server_name example.com; # 無 www
# 統一加 www
return 301 https://www.example.com$request_uri;
}
server {
listen 443 ssl http2;
server_name www.example.com; # 規範主機名
# ... 正常 PHP 處理
location ~ \.php$ {
fastcgi_pass unix:/run/php/php-fpm.sock;
include fastcgi_params;
}
}
Apache (.htaccess)
RewriteEngine On
# 強制 HTTPS
RewriteCond %{HTTPS} off
RewriteRule ^ https://%{HTTP_HOST}%{REQUEST_URI} [R=301,L]
# 統一加 www
RewriteCond %{HTTP_HOST} !^www\. [NC]
RewriteRule ^ https://www.%{HTTP_HOST}%{REQUEST_URI} [R=301,L]
常見陷阱與避坑
| 問題 | 原因 | 解決 |
| 重定向循環 | PHP 與 Nginx 都做重定向、或條件判斷錯誤 | 統一在一層處理(建議 Nginx),PHP 僅作備用 |
| POST 數據丟失 | 301 重定向瀏覽器會將 POST 轉為 GET | 表單直接提交到規範 URL;API 端點不做 301 |
| 查詢字串丟失 | Location 未包含 REQUEST_URI | 必須附加 $request_uri / %{REQUEST_URI} |
| SEO 權重未傳遞 | 使用 302 而非 301 | 明確發送 301 Moved Permanently |
SEO 檢查清單
- ✅ 所有舊域名/非規範域名 301 到規範域名。
- ✅ HTTP 全站 301 到 HTTPS。
- ✅ 規範 URL 一致性(www vs 非 www、斜槓結尾)。
- ✅ Google Search Console 提交變更地址工具。
- ✅ 更新 Sitemap、內部鏈接、Canonical 標籤指向規範 URL。
copyright ©
萬盛學電腦網 all rights reserved