2016-06-30 18 views
5

我正在使用Yii2,我想使用帶路由的urlManager將所有非字母和非數字字符轉換爲斜線。我已經看過很多問題(#1,#2,#3,#3,#4),但沒有一個解決它,因爲它們或者顯示有點類似,但不是我想要或者根本不爲我工作。Yii2漂亮的URL:自動將所有內容以斜線(包括所有參數)進行轉換

我有簡單的urlManager規則:

//... 
'urlManager' => [ 
    'class' => 'yii\web\UrlManager', 
    'enablePrettyUrl' => true, 
    'showScriptName' => false, 
    'rules' => array(
     '<controller:\w+>/<id:\d+>' => '<controller>/view', 
     '<controller:\w+>/<action:\w+>/<id:\d+>' => '<controller>/<action>', 
     '<controller:\w+>/<action:\w+>' => '<controller>/<action>', 
    ), 
], 

的.htaccess(也很簡單):

RewriteEngine on 
# If a directory or a file exists, use it directly 
RewriteCond %{REQUEST_FILENAME} !-f 
RewriteCond %{REQUEST_FILENAME} !-d 
# Otherwise forward it to index.php 
RewriteRule . index.php 

就我而言,我的醜陋的網址是這個(SiteController -> public function actionTestRouter()):

localhost/frontend/web/index.php?r=site%2Ftest-router&ident=10&token=ADB&module=P120

根據我上面寫的規則,我得到了更好的結果(因爲它刪除了index.php?r=並將其轉換%2F/):

localhost/frontend/web/site/test-router?ident=10&token=ADB&module=P120

我想什麼:

localhost/frontend/web/site/test-router/ident/10/token/ADB/module/P120

我的幾個attemps的規則是:

'test-route/<ident:\d+>/<token:\w+>/<module:\w+>' => 'test-route' // 1 
'<controller:\w+>/<action:\w+>/<ident:\d+>/<token:\w+>/<module:\w+>' => '<controller>/<action>' // 2 
'<controller:\w+>/<action:\w+>/<slug:[a-zA-Z0-9_-]+>/' => '<controller>/<action>/<slug>' // 3 (not even sure what slug does here 

這也將是超好聽如果規則將適用到任何參數和值,而不管它們的名稱和值如何。

回答

5

你的第二次嘗試

'<controller:[\w\-]+>/<action:[\w\-]+>/<ident:\d+>/<token:\w+>/<module:\w+>' => '<controller>/<action>' // 2 

將採取/創建URL

localhost/frontend/web/site/test-router/10/ADB/P120

沒有網址參數的名稱和這些PARAMS將在這個順序只能用,當你看到他們的名單是固定的

如果你想在url中添加它們的名字(用於你的問題中的estetic或seo目的):

'<controller:[\w\-]+>/<action:[\w\-]+>/ident/<ident:\d+>/token/<token:\w+>/module/<module:\w+>' => '<controller>/<action>', // 2 

和URL創建這些路線將是相同的:

echo Url::to(['site/test-router', 'ident' => 100, 'module' => 100, 'token' => 100]); 

如果你想解析則params的這個名單的各種長度,你可以使用水木清華這樣的:

'<controller:[\w\-]+>/<action:[\w\-]+>/<params:[a-zA-Z0-9_\-\/]+>' => '<controller>/<action>' 

或指定它只針對一條路線:

'site/test-route/<params:[a-zA-Z0-9_\-\/]+>' => 'site/test-route' 

因此,在行動中,您將獲得參數paramsYii::$app->request->get('params');用正則表達式解析它。

+0

感謝您的回答。但是我得到了這個錯誤:'preg_match():編譯失敗:嘗試最後一個或倒數第二個選項時,在偏移量爲66'的字符類中的順序失序。 :/ –

+0

啊自5.2以後也應該逃脫。回答編輯。 – user1852788

+0

我仍然不明白。:/我嘗試了編輯並輸入了'localhost/frontend/web/site/test-router/ident/10/token/ADB/module/P120'(直接進入URL),但是我得到了'404'錯誤。 –

相關問題