萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> PHP 程式設計

PHP 偽靜態實現指南:Apache Rewrite 與 PHP PATH_INFO 兩大方案

偽靜態(URL Rewrite)讓動態 PHP 頁面呈現靜態 HTML 形式的 URL,利於 SEO、用戶體驗與安全性。主流方案有二:Web 服務器層面的 Rewrite(Apache/Nginx)與 PHP 內部的 PATH_INFO 解析。本文詳細對比兩種方案的配置與代碼實現。

方案一:Apache mod_rewrite(推薦)

1. 啟用模塊

編輯 httpd.conf,取消註釋:

LoadModule rewrite_module modules/mod_rewrite.so

並確保目錄允許覆蓋:AllowOverride All

2. .htaccess 規則編寫

在網站根目錄創建 .htaccess:

RewriteEngine On

# 根目錄訪問重寫到 index.php
RewriteRule ^$ index.php [L]

# 文章頁:article-123.html → article.php?id=123
RewriteRule ^article-([0-9]+)\.html$ article.php?id=$1 [L]

# 分頁:list-5-2.html → list.php?cid=5&page=2
RewriteRule ^list-([0-9]+)-([0-9]+)\.html$ list.php?cid=$1&page=$2 [L]

# 通用 REST 風格:/user/123/profile → index.php?m=user&id=123&a=profile
RewriteRule ^([a-z]+)/([0-9]+)/([a-z]+)$ index.php?m=$1&id=$2&a=$3 [L]

3. 正則捕獲組引用

  • $1、$2... 對應正則中第 1、2 個 () 捕獲組
  • [L] 旗標表示最後一條規則,匹配後停止後續匹配
  • [NC] 不區分大小寫,[QSA] 追加原查詢字符串

4. 重啟 Apache 生效

systemctl restart httpd  # 或 apache2ctl restart

方案二:PHP PATH_INFO 解析(無需服務器配置)

利用 $_SERVER['PATH_INFO'] 獲取腳本名之後的路徑信息。

訪問 URL 示例

https://example.com/soft.php/1,100,8630.html
// $_SERVER['PATH_INFO'] = '/1,100,8630.html'

解析代碼

<?php
if (isset($_SERVER['PATH_INFO'])) {
    $pathInfo = $_SERVER['PATH_INFO']; // 如 /1,100,8630.html
    
    // 正則提取參數
    if (preg_match('#/(\d+),(\d+),(\d+)\.html#', $pathInfo, $matches)) {
        $gid    = (int)$matches[1]; // 1
        $sid    = (int)$matches[2]; // 100
        $softid = (int)$matches[3]; // 8630
        
        // 現在可像處理 $_GET 一樣使用
        // 相當於 soft.php?gid=1&sid=100&softid=8630
    } else {
        die('Path: Error!');
    }
} else {
    die('Path: Nothing!');
}
?>

兩大方案深度對比

| 維度 | Apache Rewrite | PHP PATH_INFO | |------|----------------|---------------| | **配置權限** | 需服務器配置權限 | 僅需 PHP 權限,虛擬主機友好 | | **效能** | 服務器層面處理,無 PHP 開銷 | 請求進入 PHP 後解析,微小開銷 | | **靈活性** | 正則強大,支援複雜重寫 | PHP 代碼控制,邏輯極其靈活 | | **調試** | 需查錯誤日誌、RewriteLog | 直接 var_dump 輸出調試 | | **遷移性** | 需重寫 Nginx 配置 | 純 PHP,跨服務器零配置 | | **SEO 友好** | 完美支援靜態化 URL | 同樣支援,但 URL 含腳本名 |

Nginx 環境下的偽靜態(補充)

現代主流 Nginx 配置:

location / {
    try_files $uri $uri/ /index.php?$query_string;
}

# 特定規則
rewrite ^/article-(\d+)\.html$ /article.php?id=$1 last;
rewrite ^/list-(\d+)-(\d+)\.html$ /list.php?cid=$1&page=$2 last;

最佳實踐建議

  1. 生產環境首選 Web 服務器 Rewrite:效能最優、邏輯分離清晰
  2. 虛擬主機/無服務器權限:使用 PATH_INFO 或框架內置路由
  3. 框架開發:Laravel/ThinkPHP/Symfony 內置優雅路由,無需手寫規則
  4. URL 設計原則:短、語義化、層級清晰、小寫、連字符分隔

總結

Apache mod_rewrite 是偽靜態的工業標準,配置一次受益全站;PATH_INFO 是無服務器權限時的靈活備選。理解正則捕獲組映射、[L]/[QSA] 旗標含義、Nginx try_files 機制,能讓你在任何環境下優雅實現 SEO 友好的靜態化 URL。

copyright © 萬盛學電腦網 all rights reserved