將 URL 從 https://example.com/index.php?r=site/index 簡化為 https://example.com/site/index。
web/index.php 為入口web/urlManager.enablePrettyUrl = true、showScriptName = falseserver {
listen 80;
server_name example.com;
root /var/www/yii2/web; # 指向 web 目錄
index index.php;
location / {
# 嘗試直接服務檔案,否則導向 index.php
try_files $uri $uri/ /index.php$is_args$args;
}
location ~ \.php$ {
fastcgi_pass unix:/run/php/php8.2-fpm.sock; # 或 127.0.0.1:9000
fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
include fastcgi_params;
fastcgi_intercept_errors on;
}
# 安全:隱藏隱藏檔、版本控制目錄
location ~ /\.(htaccess|htpasswd|git|svn) {
deny all;
}
}
放置於 web/.htaccess:
RewriteEngine On
# 如果請求是實際存在的檔案/目錄,直接服務
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
# 否則導向 index.php 保留查詢字串
RewriteRule ^(.*)$ index.php [L,QSA]
# 安全:禁止存取隱藏檔
Order allow,deny
Deny from all
# 可選:強制 HTTPS
# RewriteCond %{HTTPS} off
# RewriteRule ^ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]
return [
'components' => [
'request' => [
'baseUrl' => '', // 關鍵:移除腳本名稱前綴
],
'urlManager' => [
'enablePrettyUrl' => true,
'showScriptName' => false,
'enableStrictParsing' => false,
'rules' => [
'' => 'site/index',
'/' => '/',
'//' => '//',
// RESTful API
['class' => 'yii\rest\UrlRule', 'controller' => 'user'],
],
],
],
];
| 現象 | 原因 | 解決 |
|---|---|---|
| 404 Not Found | Nginx 未正確傳遞 SCRIPT_FILENAME | 確認 fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name; |
| 無限重定向 | rewrite 規則錯誤導向自身 | 檢查 try_files 順序、去除多餘 rewrite |
| CSS/JS/圖片 404 | root 指向錯誤目錄 | root 必須指向 web/ 目錄 |
| 參數丟失 | QSA 旗標缺失 | RewriteRule 加 [QSA] |
location /yii2/ {
alias /var/www/yii2/web/; # 必須用 alias 並以 / 結尾
try_files $uri $uri/ /yii2/index.php$is_args$args;
location ~ \.php$ {
fastcgi_pass unix:/run/php/php8.2-fpm.sock;
fastcgi_param SCRIPT_FILENAME $request_filename; # alias 時用 $request_filename
include fastcgi_params;
}
}