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

利用 PATH_INFO 實現搜尋引擎友好 URL 並隱藏 index.php

     編輯:PHP 相關知識

為什麼要用 PATH_INFO?

傳統 PHP 應用常見 URL 如 index.php?module=user&action=login,不利 SEO 且語意不明。採用 PATH_INFO 可產出類似靜態頁的結構化路徑:

https://www.example.com/index.php/module/user/action/login/id/123

進一步隱藏 index.php,即可得到乾淨的 RESTful 風格 URL:

https://www.example.com/module/user/action/login/id/123

Apache 設定:隱藏副檔名並啟用 PATH_INFO

1. 讓無副檔名的腳本被 PHP 解析

在虛擬主機或 .htaccess 中加入:

<Files "index">
    ForceType application/x-httpd-php
</Files>

或針對整個目錄:

ForceType application/x-httpd-php

如此 https://example.com/index/foo/bar 會由 index(實為 PHP 腳本)處理,$_SERVER['PATH_INFO'] 為 /foo/bar。

2. Apache 2.x 必須開啟 AcceptPathInfo

AcceptPathInfo On

預設關閉會導致 404 錯誤。

3. 進階:模擬靜態 HTML 結尾

若想要 https://example.com/app_name/my/app.html 這樣的偽靜態,可在解析 PATH_INFO 時,截斷最後 5 字元 .html:

<?php
$pathInfo = $_SERVER['PATH_INFO'] ?? '';
if (substr($pathInfo, -5) === '.html') {
    $pathInfo = substr($pathInfo, 0, -5);
}
// 接著依 '/' 分割路由參數
$segments = explode('/', trim($pathInfo, '/'));
?>

完整 .htaccess 範例(適用共享主機)

RewriteEngine On
# 若請求非實體檔案/目錄,導向 index.php
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php/$1 [L,QSA]

# 啟用 PATH_INFO(部分主機需在 httpd.conf 設定)
AcceptPathInfo On

PHP 端路由解析建議

<?php
// 統一入口 index.php
$pathInfo = $_SERVER['PATH_INFO'] ?? $_SERVER['REQUEST_URI'] ?? '';
// 移除查詢字串
$pathInfo = parse_url($pathInfo, PHP_URL_PATH);
// 移除開頭的 /index.php
$pathInfo = preg_replace('#^/index\.php#', '', $pathInfo);
// 移除 .html 結尾
$pathInfo = preg_replace('#\.html$#', '', $pathInfo);
// 分段
$segments = array_values(array_filter(explode('/', $pathInfo)));

// 簡易路由映射
$routes = [
    'module' => $segments[0] ?? 'default',
    'action' => $segments[1] ?? 'index',
    'id'     => $segments[2] ?? null,
];

// 載入對應 Controller
$controller = ucfirst($routes['module']) . 'Controller';
$action     = $routes['action'] . 'Action';
if (class_exists($controller)) {
    $ctl = new $controller();
    if (method_exists($ctl, $action)) {
        $ctl->$action($routes['id']);
    }
}
?>

注意事項

  • 相對路徑失效:HTML 中的 CSS/JS/圖片路徑需改為絕對路徑(/assets/style.css)或使用 <base href="/">。
  • 雙重編碼問題:中文路徑經過 Rewrite 可能被雙重 URL encode,需在 PHP 端 urldecode() 處理。
  • 效能:PATH_INFO 解析極快,但大量 Rewrite 規則會增加 Apache 負擔;高流量建議改用 Nginx + try_files。

結語

PATH_INFO 是 PHP 時代實現美觀、SEO 友好 URL 的經典技術,配合 ForceType 與 AcceptPathInfo On 即可輕鬆隱藏 index.php 甚至模擬靜態結尾。現代專案若採用 Laravel、Symfony 等框架,路由元件已內建更完善的解析與生成機制,建議直接使用框架提供的路由功能。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved