[Yii2] 佈署子目錄網址架構(Route SubDirectory) – 設定 $request->baseUrl、修正Url與PrettyUrl

Yii2部屬上,如果不是在Domain根目錄,要部屬Yii2恐造成Base Url錯亂及PrettyUrl後的Route吃不進Yii。

例如,在Nginx location目錄名與實體uri(Sub document root in location)不一樣下,預設的Yii其Base Url會以uri為主而非Nginx location目錄名,另外PrettyUrl因為無法正確比對REQUEST_URI導致Route無法解析。

  • 基本影響層級,Url可能是取自DOCUMENT_URI
\yii\helpers\Url::to(['/']);
\yii\helpers\Url::home();

【解決方法】:

在Yii2 config -> request component -> baseUrl 設定基礎目錄(同Nginx location目錄名),以讓Yii依此套用全部基礎Url,也才能依此路徑去比對REQUEST_URI取得Route。

$config = [
    'components' => [
        'request' => [
            'cookieValidationKey' => '',
            'baseUrl' => '/subdir'
        ],
    ]
]

另外,Web Server上需做try_file至當前index.php,給個Nginx範例:

location /subdir/ {
    # Redirect everything that isn't a real file to index.php
    try_files $uri $uri/ /subdir/web/index.php$is_args$args;
}

目錄保護的子目錄site建法

請參考:Yii2 Server Configuration for Nginx & Apache (Subdirectory)

Leave a Reply

Your email address will not be published. Required fields are marked *