当前位置: 首页 > 后端技术 > PHP

Yii2框架URL美化教程

时间:2023-03-29 17:26:00 PHP

Yii2.0默认访问形式为:http://www.xxx.com/index.php?r=post/index&id=100一般我们会考虑美化一下,变成如下形式:http://www.xxx.com/post/100.html接下来就是美化步骤1.配置http服务器1.Apache在入口文件(index.php)所在目录新建一个文本文件)找到,然后另存为.htaccess,用编辑器打开这个文件并添加:RewriteEngineonRewriteCond%{REQUEST_FILENAME}!-fRewriteCond%{REQUEST_FILENAME}!-dRewriteRule^(.*)$index.php[L,E=PATH_INFO:$1]保存2.在nginx配置文件中添加nginx(我的本地文件是/conf/vhosts/test.conf):location/{try_files$uri$uri//index.php?$query_string;}的整个服务器配置类似:server{listen80;server_nametest.yii.com;根“/Projects/yii/web”;location/{indexindex.htmlindex.htmindex.php;try_files$uri$uri//index.php?$query_string;}error_page/50x.html;location=/50x.html{根html;}location~\.php(.*)${fastcgi_pass127.0.0.1:9000;fastcgi_indexindex.php;fastcgi_split_path_info^((?U).+\.php)(/?.*)$;fastcgi_paramSCRIPT_FILENAME$document_root$fastcgi_script_name;fastcgi_paramPATH_INFO$fastcgi_path_info;fastcgi_paramPATH_TRANSLATED$document_root$fastcgi_path_info;config=['components'=>[]],添加如下内容:'urlManager'=>[//启用url美化'enablePrettyUrl'=>true,//隐藏index.php'showScriptName'=>false,//DisableStrictmatchingmode'enableStrictParsing'=>false,//url后缀名'suffix'=>'.html',//urlrule'rules'=>[//post后跟一个数字url,则数字为赋值给id参数,然后传给post/view,实际访问post/view?id=XXX'post/'=>'post/view']],在rules中配置具体的路由规则array3.重启http服务器此时,配置完成后,http服务器中配置的虚拟域名必须直接指向入口文件所在目录。否则,如果url中省略了index.php,http服务器将无法正确访问该项目。例如:配置test.yii.com虚拟域名指向/Projects/yii/web目录,而你的项目入口文件实际上是在/Projects/yii/web/test目录下。浏览器访问项目的url为:http://test.yii.com/test/index.php?r=post/view&id=100这时候把url改成http://就不行了/test.yii.com/test/post/100.html