首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 網頁程式設計 >> PHP 程式設計 >> PHP 綜合知識

PHP 偽靜態實作:PATH_INFO 模式與 URL 重寫完整指南

     編輯:PHP 綜合知識

PHP 偽靜態技術全解析:從 PATH_INFO 到 URL Rewrite

偽靜態讓動態網址呈現靜態頁面樣貌 (如 /article/123.html),兼具 SEO 友善與動態彈性。本文詳細說明兩大主流實作方式:PATH_INFO 與 Web Server Rewrite。

方式一:PATH_INFO (無需 Web Server 設定)

PHP 內建支援 $_SERVER['PATH_INFO'] 取得腳本路徑後的額外路徑資訊。

URL 格式

https://example.com/index.php/article/123.html
https://example.com/index.php/user/profile/456

核心解析代碼

<?php
$pathInfo = $_SERVER['PATH_INFO'] ?? '';

// 範例:匹配 /article/123.html 格式
if (preg_match('~^(/[a-z]{1,16})\\.([0-9]{1,16})\\.html$~', $pathInfo, $matches)) {
    // $matches[0] = 完整匹配 /article/123.html
    // $matches[1] = /article
    // $matches[2] = 123
    
    $action = ltrim($matches[1], '/'); // 'article'
    $id     = (int)$matches[2];        // 123
    
    // 當作 $_GET 使用
    $_GET['action'] = $action;
    $_GET['id']     = $id;
    
    echo "Action: $action, ID: $id";
} else {
    echo "404 Not Found";
}
?>

PATH_INFO 優缺點

優點 缺點
無需修改 Apache/Nginx 設定 網址含 index.php 不夠美觀
PHP 內建支援,相容性高 部分舊版 CGI/FastCGI 模式不支援
部署簡單,複製檔案即可 不利 SEO (搜尋引擎偏好乾淨網址)

方式二:Web Server URL Rewrite (推薦生產環境)

由 Web Server 將美觀網址內部重寫至 PHP 腳本,瀏覽器網址列保持乾淨。

Apache .htaccess

RewriteEngine On
RewriteBase /

# 存在的檔案/目錄直接服務
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d

# 核心重寫規則
# 範例:/article/123.html → index.php?action=article&id=123
RewriteRule ^([a-z]+)/([0-9]+)\.html$ index.php?action=$1&id=$2 [L,QSA]

# 通用規則:所有請求導向 index.php (前端控制器模式)
# RewriteRule ^(.*)$ index.php?route=$1 [L,QSA]

Nginx 設定

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

# 或特定規則
location ~ ^/([a-z]+)/([0-9]+)\.html$ {
    rewrite ^/([a-z]+)/([0-9]+)\.html$ /index.php?action=$1&id=$2 last;
}

PHP 端統一處理 (前端控制器模式)

<?php
// index.php - 統一入口
$route = $_GET['route'] ?? $_SERVER['REQUEST_URI'];

// 解析路由
$routes = [
    'article/(\d+)\.html' => 'ArticleController::show',
    'user/(\d+)'          => 'UserController::profile',
    'category/([^/]+)'    => 'CategoryController::list',
];

foreach ($routes as $pattern => $handler) {
    if (preg_match('~^' . $pattern . '$~', $route, $matches)) {
        array_shift($matches); // 移除完整匹配
        // 呼叫控制器: call_user_func($handler, ...$matches)
        echo "Handler: $handler, Params: " . implode(', ', $matches);
        exit;
    }
}

http_response_code(404);
echo "404 Not Found";
?>

進階:RESTful 風格路由設計

HTTP Method URL Controller Action 說明
GET /articles index 文章列表
GET /articles/123 show 單篇文章
POST /articles store 新增文章
PUT/PATCH /articles/123 update 更新文章
DELETE /articles/123 destroy 刪除文章

推薦成熟路由庫

  • FastRoute:尼基塔·波波夫 (PHP 核心開發) 作品、極速、Composer 安裝
  • League/Route:PSR-7/15 相容、中介軟體支援
  • Symfony Routing:功能完整、註解/屬性/ YAML/ XML 定義
  • Laravel Router:框架內建、語法優雅、模型綁定

偽靜態 SEO 優化清單

  • ✅ 網址包含關鍵字:/article/php-pseudo-static-guide
  • ✅ 使用連字號 - 分隔單字,非底線
  • ✅ 避免過長網址 (建議 < 100 字元)
  • ✅ 統一大小寫 (全小寫)
  • ✅ 設定 Canonical 標籤防重複內容
  • ✅ 301 重導向舊網址 (如從 PATH_INFO 遷移至 Rewrite)
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved