jason_king 2015-08-20 11:17:57 9926次浏览 7条评论 9 1 0

Yii 框架的访问地址若不简化会让人觉得很繁琐,未简化的地址一般格式如下:
http://localhost:80/test/index.php?r=xxx/xxx/xxx
若是带有参数会更复杂:
http://localhost:80/test/index.php?r=xxx/xxx/xxx&param1=XXX&param2=XXX

那么我们通过什么方法把它美化下呢:
1.在config文件夹下的main.php文件内,找到urlManager的配置,修改为如下:

'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>',
			'<controller:\w+>/<action:\w+>'=>'<controller>/<action>',
		),
	),
),

现在再来访问你的项目,你就会发现你的项目URL变成了:
http://localhost:80/test/index.php/XXX/XXX

2.这和不够,我们想继续简化,把index.php也去掉。继续修改main.php文件,

'urlManager'=>array(
	'urlFormat'=>'path',
	'showScriptName'=>false, //去除index.php
	//'urlSuffix'=>'.html', //加上.html  
	'rules'=>array(
		'<controller:\w+>/<id:\d+>'=>'<controller>/view',
		'<controller:\w+>/<action:\w+>/<id:\d+>'=>'<controller>/<action>',
		'<controller:\w+>/<action:\w+>'=>'<controller>/<action>',
		'<controller:\w+>/<action:\w+>'=>'<controller>/<action>',
	),
),

这么修改之后,index.php不见了,但是会发现,部分URL出错了。怎么解决呢?

3.添加 .htaccess文件,用于项目的访问。内容如下:

<IfModule mod_rewrite.c> 

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

</IfModule>

这样进入项目就会自动访问index.php文件,url就不会错乱了。

最后简化后的URL如下:
http://localhost:80/test/XXX/XXX

觉得很赞
您需要登录后才可以评论。登录 | 立即注册