[英]I'm trying to beautify an URL in Yii
由於我已經完成了項目,因此無法理解美化的url。 假設這是我的網址:
localhost/wowwaylabs/trunk/mpi_v1/index.php?r=products/index&catId=1
產品是控制器,索引是該控制器的操作。 catId是我通過網址傳遞的參數。 我需要美化網址
localhost/wowwaylabs/trunk/mpi_v1/this-is-india-1
其中1是我經過的catId。
為了使url美觀,您需要在.htaccess文件中添加以下代碼行,這些文件應位於項目的根文件夾中:
Options +FollowSymLinks
IndexIgnore */*
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
它將保留您的url而不顯示?r。
現在取消注釋以下內容以啟用路徑格式的URL(在protected / config / main.php中)
/*
'urlManager'=>array(
'urlFormat'=>'path',
'rules'=>array(
'<controller:\w+>/<id:\d+>'=>'<controller>/view',
'<controller:\w+>/<action:\w+>/<id:\d+>'=>'<controller>/<action>',
'<controller:\w+>/<action:\w+>'=>'<controller>/<action>',
),
),
*/
然后在同一文件的“ urlManager”中添加'showScriptName'=>false,
。 它將從網址中刪除index.php。
有關更多信息,請檢查以下鏈接:
http://www.yiiframework.com/doc/guide/1.1/en/topics.url
http://www.sniptrichint.com/tip-of-the-day/beautiful-url-in-yii-without-index/
我認為它將解決您的問題。
假設“ this-is-india
是變量或任意長度(例如,類別名稱的長度或語法可能有所不同,如Pitchinnate在評論中所建議的那樣),那么您可以完全使用url管理器執行此操作,而無需像這樣編輯htaccess :
'urlManager'=>array(
...
'rules'=>array(
'<catName:[0-9a-zA-Z_\-]+>-<catId:\d+>'=>'products/index',
...
),
...
),
這將采用字符的任意組合,並以數字結尾,並將數字結尾用作catId
,例如:
localhost/wowwaylabs/trunk/mpi_v1/this-is-india-1
將解決
localhost/wowwaylabs/trunk/mpi_v1/index.php?r=products/index&catId=1&catName=this-is-india
同樣地;
localhost/wowwaylabs/trunk/mpi_v1/this-is-another-title-or-category-or-whatever-999
將解決:
localhost/wowwaylabs/trunk/mpi_v1/index.php?r=products/index&catId=999&catName=this-is-another-title-or-category-or-whatever
通過htaccess :)
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$/? index.php?r=$1 [PT,L]
</IfModule>
localhost/wowwaylabs/trunk/mpi_v1/products/index/&catId=1
如果您已經在使用Yii的URL管理器(如果不遵循Workonphp的說明將其打開),請嘗試創建一個規則並將其添加到如下所示的規則頂部:
'<category_id:\w+>' => 'products/index',
這樣做是什么,如果在URL中僅傳遞一個參數(即類別名稱和ID),並且它是字符串/單詞(:\\ w +指定此參數)而不是數字(:\\ d +),則默認為產品控制器和索引動作。 然后它將$category_id
作為變量傳遞到控制器中。 然后,您將需要修改該操作以將id從字符串中拉出,如下所示:
public function actionIndex($category_id) {
$pieces = explode('-',$category_id);
$cat_id = end($pieces); //actual category id seperated from name
//...rest of code for this function
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.