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

Yii2 通過 .htaccess 隱藏 index.php 實現美觀 URL

     編輯:PHP 相關知識

前置條件

  • Apache 已載入 `mod_rewrite` 模塊(`LoadModule rewrite_module modules/mod_rewrite.so`)
  • 站點配置 `AllowOverride All` 允許 `.htaccess` 生效
  • Yii2 應用入口文件為 `web/index.php`(basic 模板)或 `frontend/web/index.php`(advanced)

.htaccess 完整配置

放置於 **入口文件同級目錄**(即 `web/` 或 `frontend/web/`)。

<IfModule mod_rewrite.c>
    # 禁止直接訪問 .htaccess
    <Files .htaccess>
        Order allow,deny
        Deny from all
    </Files>

    # 禁用目錄瀏覽
    Options -Indexes

    # 啟用符號鏈接跟隨(某些主機需註釋)
    Options +FollowSymLinks

    RewriteEngine On

    # 如果請求是真實存在的文件/目錄,直接服務
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME} !-d

    # 否則重寫到 index.php,保留查詢字符串
    RewriteRule ^(.*)$ index.php [L,QSA]
</IfModule>

關鍵指令解析

指令作用
RewriteCond %{REQUEST_FILENAME} !-f請求路徑**不是**現有文件
RewriteCond %{REQUEST_FILENAME} !-d請求路徑**不是**現有目錄
RewriteRule ^(.*)$ index.php [L,QSA]匹配任意路徑 → 內部轉發到 index.php;L 最後一條規則;QSA 追加原查詢參數

Yii2 應用配置配合

// config/web.php
return [
    'components' => [
        'urlManager' => [
            'enablePrettyUrl' => true,       // 啟用美觀 URL
            'showScriptName' => false,       // 隱藏 index.php
            'suffix' => '',                  // 無 .html 後綴
            'rules' => [
                '' => 'site/index',
                'post/<id:\d+>' => 'post/view',
                'category/<slug>' => 'category/view',
                // RESTful 風格
                ['class' => 'yii\rest\UrlRule', 'controller' => 'user'],
            ],
        ],
    ],
];

Nginx 對應配置(參考)

location / {
    try_files $uri $uri/ /index.php$is_args$args;
}

location ~ \.php$ {
    fastcgi_pass unix:/run/php/php8.2-fpm.sock;
    fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
    include fastcgi_params;
}

常見坑點

  • 未開啟 mod_rewrite:`a2enmod rewrite && systemctl reload apache2`
  • AllowOverride None:虛擬主機配置 ` AllowOverride All `
  • 多項目共用域名:子目錄項目需在 `RewriteRule` 加上 `RewriteBase /subdir/`
  • API 模式:若僅提供 API,建議關閉 `enablePrettyUrl`,直接用 `index.php?r=route`,避免重寫衝突。

驗證方法

  1. 訪問 `https://domain.com/controller/action`(無 index.php)
  2. 檢查 `Yii::$app->request->url` 獲取路由是否正確解析
  3. 使用 `Url::to(['post/view', 'id' => 1])` 生成鏈接,應輸出 `/post/1`

總結

`.htaccess` + `urlManager` 兩步即可實現 Yii2 美觀 URL。核心在於**重寫條件精準匹配**與**組件配置關閉腳本名顯示**。Nginx 環境下同理配置 `try_files`。

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