Yii2框架URL美化教程

Yii2.0默认的访问形式为:

http://www.xxx.com/index.php?r=post/index&id=100

一般我们都会考虑将其美化一下,变成如下的形式:

http://www.xxx.com/post/100.html

接下来就是美化的步骤

一、配置http服务器

1、Apache

在入口文件(index.php)所在的目录下新建一个文本文件,接着另存为.htaccess,用编辑器打开此文件加入:

RewriteEngine on
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php [L,E=PATH_INFO:$1]

保存即可

2、Nginx

在nginx配置文件(我本地是/conf/vhosts/test.conf文件)中加入:

location/{
    try_files $uri $uri/ /index.php?$query_string;
}

整个server配置类似:

server {
        listen80;
        server_name  test.yii.com;

        root "/Projects/yii/web";
        location / {
            index  index.html index.htm index.php;
            try_files $uri $uri/ /index.php?$query_string;
        }

        error_page /50x.html;
        location = /50x.html {
            root   html;
        }

        location~ \.php(.*)$ {
            fastcgi_pass 127.0.0.1:9000;
            fastcgi_index  index.php;
            fastcgi_split_path_info ^((?U).+\.php)(/?.*)$;
            fastcgi_param  SCRIPT_FILENAME  $document_root$fastcgi_script_name;
            fastcgi_param  PATH_INFO  $fastcgi_path_info;
            fastcgi_param  PATH_TRANSLATED  $document_root$fastcgi_path_info;
            include        fastcgi_params;
        }
    }

二、配置yii

打开config目录下的web.php,在$config = [ 'components'=>[] ]中加入以下内容:

'urlManager' => [
    //开启url美化
    'enablePrettyUrl' => true,
    //隐藏index.php
    'showScriptName' => false,
    //禁用严格匹配模式
    'enableStrictParsing' => false,
    //url后缀名称
    'suffix'=>'.html',
    //url规则
    'rules' => [
        //post后面跟上数字的url,则将数字赋给id参数,然后传递给 post/view,实际上访问的是 post/view?id=XXX
        'post/'=>'post/view'
    ]
],

rules数组中配置具体的路由规则

三、重启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

是行不通的

你可能感兴趣的:(yii2,php,php框架,url-rewrite)