萬盛學電腦網

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

ThinkPHP pathinfo 模式與 URL 重寫完整配置指南

Pathinfo 模式原理

URL 格式:https://serverName/appName/module/action/param1/value1/param2/value2/

  • 無 `index.php`,路徑信息直接附加在入口文件後。
  • ThinkPHP 解析 `$_SERVER['PATH_INFO']` 獲取模塊、控制器、操作及參數。
  • 參數必須成對出現(key/value)。

URL 重寫:隱藏 index.php

通過 Web 服務器重寫模塊將請求內部轉發到 `index.php`,實現更優雅的 URL。

Apache 配置(.htaccess)

  1. 確保 `httpd.conf` 加載 `mod_rewrite.so`:`LoadModule rewrite_module modules/mod_rewrite.so`
  2. 將目錄 `AllowOverride None` 改為 `AllowOverride All`。
  3. 入口文件同級目錄創建 `.htaccess`:
<IfModule mod_rewrite.c>
    RewriteEngine on
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteRule ^(.*)$ index.php/$1 [QSA,PT,L]
</IfModule>

Nginx 配置

location / {
    if (!-e $request_filename) {
        rewrite ^(.*)$ /index.php/$1 last;
        break;
    }
}
# 或更標準的 try_files
location / {
    try_files $uri $uri/ /index.php$is_args$args;
}

location ~ \.php($|/) {
    fastcgi_pass unix:/run/php/php-fpm.sock;
    fastcgi_split_path_info ^(.+\.php)(/.+)$;
    fastcgi_param PATH_INFO $fastcgi_path_info;
    fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
    include fastcgi_params;
}

ThinkPHP 配置

'url_model' => 2, // 1=普通, 2=pathinfo, 3=rewrite, 4=兼容
'url_html_suffix' => 'html', // 可選偽靜態後綴
'url_route_on' => true, // 開啟路由

對比總結

模式URL 示例優點缺點
普通 (0/1)?m=Home&c=Index&a=index兼容性最好,無需服務器配置不美觀、SEO 弱
Pathinfo (2)/Home/Index/index/id/1語義清晰、SEO 友好、無需重寫URL 中含 index.php(未重寫時)
Rewrite (3)/Home/Index/index/id/1最美觀、SEO 最佳、隱藏入口需服務器支持重寫模塊

常見問題排查

  • 404 錯誤:重寫規則未生效、AllowOverride 未開啟、Nginx 未配置 `fastcgi_split_path_info`。
  • PATH_INFO 為空:Nginx 必須設置 `fastcgi_split_path_info` 並傳遞 `PATH_INFO` 參數。
  • 參數獲取異常:檢查 `I('param.')` 或 `$_GET`,確認路由規則未攔截。
  • 子目錄部署**:RewriteBase 需設置正確子目錄路徑。
copyright © 萬盛學電腦網 all rights reserved