我正在使用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
這也將是超好聽如果規則將適用到任何參數和值,而不管它們的名稱和值如何。
感謝您的回答。但是我得到了這個錯誤:'preg_match():編譯失敗:嘗試最後一個或倒數第二個選項時,在偏移量爲66'的字符類中的順序失序。 :/ –
啊自5.2以後也應該逃脫。回答編輯。 – user1852788
我仍然不明白。:/我嘗試了編輯並輸入了'localhost/frontend/web/site/test-router/ident/10/token/ADB/module/P120'(直接進入URL),但是我得到了'404'錯誤。 –