放置於 **入口文件同級目錄**(即 `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 追加原查詢參數 |
// 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'],
],
],
],
];
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;
}
`.htaccess` + `urlManager` 兩步即可實現 Yii2 美觀 URL。核心在於**重寫條件精準匹配**與**組件配置關閉腳本名顯示**。Nginx 環境下同理配置 `try_files`。