萬盛學電腦網

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

PHP 偽靜態技術原理與實現方式全解析:URL 重寫、路由解析、框架實踐

偽靜態是將動態 URL(如 index.php?id=1&page=2)偽裝成靜態頁面形式(如 article-1-2.html 或 /article/1/2)的技術。本文系統講解偽靜態原理、Apache/Nginx 重寫規則、PHP 代碼級路由解析三大實現層面,並對比優缺點。

一、核心原理:URL 重寫與路由分發

偽靜態本質上包含兩個階段:

  1. Web 伺服器層面(重寫):將外部「靜態風格」URL 內部重寫為真實腳本路徑 + 參數(index.php?params),**瀏覽器地址欄不變**
  2. PHP 應用層面(路由解析):腳本接收重寫後的請求,解析 $_SERVER['REQUEST_URI'] 或 $_GET 參數,分發到對應控制器

二、Apache .htaccess 實現(最常見)

前置條件

  • 啟用 mod_rewrite 模塊
  • AllowOverride All 允許 .htaccess 覆蓋

標準 .htaccess 規則

RewriteEngine On

# 1. 排除真實存在的文件/目錄(圖片、CSS、JS 直接訪問)
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d

# 2. 核心重寫:所有請求轉發到 index.php,原路徑作為參數
RewriteRule ^(.*)$ index.php?route=$1 [L,QSA]

# 針對特定格式的精確規則示例:
# article-123.html → index.php?action=article&id=123
RewriteRule ^article-([0-9]+)\.html$ index.php?action=article&id=$1 [L]

# page-5.html → index.php?page=5
RewriteRule ^page-([0-9]+)\.html$ index.php?page=$1 [L]

# 多參數:category-php-page-2.html → index.php?cat=php&page=2
RewriteRule ^category-([a-z]+)-page-([0-9]+)\.html$ index.php?cat=$1&page=$2 [L]

正則捕獲組對應

  • $1 對應第一個 (...),$2 對應第二個...
  • [L] (Last) 停止後續規則匹配
  • [QSA] (Query String Append) 保留原查詢字串

三、Nginx 重寫配置

server {
    listen 80;
    server_name example.com;
    root /var/www/html;
    index index.php;
    
    location / {
        # 核心:嘗試文件、目錄、最後回退到 index.php 帶參數
        try_files $uri $uri/ /index.php?$query_string;
        
        # 等價於 Apache 的:
        # if (!-f $request_filename) {
        #     rewrite ^/(.*)$ /index.php?route=$1 last;
        # }
    }
    
    location ~ \.php$ {
        fastcgi_pass unix:/run/php/php8.1-fpm.sock;
        fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
        include fastcgi_params;
    }
}

Nginx try_files 比 Apache RewriteRule 更高效、語義更清晰,推薦優先使用。

四、PHP 代碼級路由解析(無需 Web 伺服器重寫)

若無法修改 Web 伺服器配置(如共享主機),可在 PHP 入口文件解析 REQUEST_URI:

方法一:PATH_INFO 模式(需 Web 伺服器支持)

<?php
// 訪問:https://example.com/index.php/article/123
$pathInfo = $_SERVER['PATH_INFO'] ?? ''; // /article/123
$pathInfo = trim($pathInfo, '/');
$segments = explode('/', $pathInfo); // ['article', '123']

$controller = $segments[0] ?? 'index';
$action     = $segments[1] ?? 'index';
$id         = $segments[2] ?? null;

// 分發
require "controllers/{$controller}.php";
?>

方法二:REQUEST_URI 解析(通用,無需 PATH_INFO 支持)

<?php
$requestUri = $_SERVER['REQUEST_URI']; // /index.php/article/123?foo=bar
// 1. 去除查詢字串
$path = parse_url($requestUri, PHP_URL_PATH); // /index.php/article/123
// 2. 去除入口腳本名
$scriptName = $_SERVER['SCRIPT_NAME']; // /index.php
$routePath = substr($path, strlen($scriptName)); // /article/123
$routePath = trim($routePath, '/');

// 3. 解析路由
if ($routePath === '') {
    $controller = 'index'; $action = 'index';
} else {
    $segments = explode('/', $routePath);
    $controller = $segments[0];
    $action = $segments[1] ?? 'index';
    $params = array_slice($segments, 2);
}

// 4. 兼容傳統 ?id=1 參數
$_GET = array_merge($_GET, array_combine(['id', 'page', 'action'], $params));
?>

方法三:正則路由映射(現代框架核心思想)

<?php
$routes = [
    'GET /'                    => ['HomeController', 'index'],
    'GET /article/{id:\d+}'    => ['ArticleController', 'show'],
    'POST /article'            => ['ArticleController', 'store'],
    'GET /category/{slug}'     => ['CategoryController', 'index'],
];

$method = $_SERVER['REQUEST_METHOD'];
$path   = parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH);

foreach ($routes as $pattern => $handler) {
    [$routeMethod, $routePath] = explode(' ', $pattern, 2);
    if ($method !== $routeMethod) continue;
    
    // 將 {param:regex} 轉換為正則
    $regex = preg_replace('/\{(\w+)(?::([^}]+))?\}/', '(?P<$1>$2)', $routePath);
    $regex = '@^' . $regex . '$@';
    
    if (preg_match($regex, $path, $matches)) {
        // 過濾數字索引,保留命名捕獲組
        $params = array_filter($matches, 'is_string', ARRAY_FILTER_USE_KEY);
        [$controller, $action] = $handler;
        // 實例化控制器、調用方法、注入參數...
        break;
    }
}
?>

五、偽靜態 vs 真靜態 vs 前後端分離

維度偽靜態真靜態 (生成 HTML)前後端分離 (SPA/SSR)
URL 形式/article/123.html/article/123.html (實際文件)/article/123 (前端路由) /api/article/123
服務端壓力每請求執行 PHP極低(直接發送文件)API 請求執行 PHP/Node/Go
數據實時性實時需重新生成實時
SEO 友好度高最高SSR 高,CSR 需預渲染
部署複雜度低(需 Rewrite)中(生成部署流程)高(構建、節點、SSR)
適用場景內容型站點、SEO 敏感、中小流量

六、安全提示:偽靜態不等於安全

  • 偽靜態**不防止 SQL 注入/XSS/CSRF**,參數最終仍進入 $_GET/$_REQUEST
  • 必須在控制器層做**參數驗證、類型轉換、預處理語句**
  • 避免在重寫規則中直接拼接 SQL(文中提到的「構造中轉注入頁面」屬於攻擊手法,非防禦)

總結

  1. Apache:.htaccess + RewriteRule + QSA 旗標
  2. Nginx:try_files $uri $uri/ /index.php?$query_string 一行搞定
  3. PHP 代碼級:解析 REQUEST_URI、PATH_INFO、正則路由表
  4. 現代框架(Laravel/Symfony/ThinkPHP)已內建完整路由系統,**無需手寫重寫規則**
  5. 偽靜態核心價值:**美觀 URL + SEO + 向後兼容**,而非安全防禦

掌握三層實現方式,根據部署環境靈活選擇,讓 URL 既漂亮又可控。

copyright © 萬盛學電腦網 all rights reserved