dd

YII url美化管理

jerry Yii 2015年08月23日 收藏

caseSensitive: 是否大小写敏感,默认使用CUrlManager::caseSensitive,即为null。
defaultParams: 该规则使用的默认get参数。当使用该规则来解析一个请求时,这个参数的值会被注入到$_GET参数中。
matchValue: 当创建一个URL时,GET参数是否匹配相应的子模式。默认使用CurlManager::matchValue,即为null。如果该属性为 false,那么意味着当路由和参数名匹配给定的规则时,将以此来创建一个URL。如果该属性为true,那么给定的参数值夜必须匹配相应的参数子模式。注意:将此属性设置为true会降低性能。

test.com/nvku想生成test.com/nvku/
'urlSuffix'=>'/',

要更改URL格式,我们应该配置urlManager应用元件,以便createUrl可以自动切换到新格式和应用程序可以正确理解新的网址:

'urlManager' => array(  
    'urlFormat' => 'path',  
    'showScriptName' => false, //隐藏index.php    
    'urlSuffix' => '.html', //后缀    
    'caseSensitive' => true, //设置对大小写不敏感  
    'rules' => array(  
        '<controller:\w+>/<id:\d+>' => '<controller>/view',  
        '<controller:\w+>/<action:\w+>/<id:\d+>' => '<controller>/<action>',  
        '<controller:\w+>/<action:\w+>' => '<controller>/<action>',  
    ),  
),

规则

'post/<id:\d+>'=>array('post/show','urlSuffix'=>'.html'),  
echo $this->createAbsoluteUrl('post/show',array('id'=>998, 'name'=>'123'));  
 输出http://localhost/yii_lab/index.php/post/998.html?name=123

 规则

'post/<id:\d+>/<mid:\w+>'=>array('post/view','urlSuffix'=>'.xml'),  
echo $this->createAbsoluteUrl('post/view',array('id'=>998, 'mid'=>'tody'));  
 输出http://localhost/yii_lab/index.php/post/998/tody.xml

  规则

'http://<user:\w+>.yiiblog.info/<_c:(look|seek)>'=>array('<_c>/host','urlSuffix'=>'.boylee'),  
 
echo $this->createAbsoluteUrl('look/host',array('user'=>'BoyLee', 'mid'=>'ny-001'));  
echo $this->createAbsoluteUrl('looks/host',array('user'=>'BoyLee', 'mid'=>'ny-001'));  
输出 http://BoyLee.yiiblog.info/look.boylee?mid=ny-001
http://localhost/yii_lab/index.php/looks/host/user/BoyLee/mid/ny-001
 
 'posts'=>'post/list',
'sayhello/<name>' => 'post/hello',  name是PostController actionHello($name)的参数
'post/<alias:[-a-z]+>' => 'post/view',   domain/post/e文小写 其中:前面的alias是PostController actionView($alias)的参数
'(posts|archive)/<order:(DESC|ASC)>' => 'post/index',  domain/posts/DESC或domain/posts/ASC
'(posts|archive)' => 'post/index',  domain/posts或domain/archive
'tos' => array('website/page', 'defaultParams' => array('alias' =>'terms_of_service')),
When the URL is /tos, pass terms_of_service as the alias parameter value.

隐藏 index.php
还有一点,我们可以做进一步清理我们的网址,即在URL中藏匿index.php 入口脚本。这就要求我们配置Web服务器,以及urlManager应用程序元件。
1.add showScriptName=>false
2.add project/.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

3.开启rewrite
简单的说,在main.php中简单设置urlManager,然后讲了3条规则,基本都覆盖到了。最后是隐藏index.php,请记住.htaccess位于index.php同级目录 ,而不是protected/目录。其他就简单了。
yii隐藏index.php不隐藏admin.php
安装那个办法确实把前台中的index.php隐藏掉了,但同时也隐藏掉了admin.php,于是进入后台的时候URL就乱套了。路径都有问题。解决办法就是:在protected/admin/config/main.php文件中加入下面一行代码:

'showScriptName' => true, 'urlSuffix'=>'/'
dd