4、URL和路由 - URL

1、定义路由

URL地址里面的index模块怎么才能省略呢,默认的URL地址显得有点长,下面就来说说如何通过路由简化URL访问。
我们在路由定义文件(application/route.php)里面添加一些路由规则,如下

默认URL访问为

http://www.tp5.com/index/index/hello/name/zhangsan.html

改造后

http://www.tp5.com/hello/zhangsan.html

在route.php里配置

return [
    'hello/[:name]' => ['index/index/hello', ['method' => 'get', 'ext' => 'html']],
];

解释:http://www.tp5.com/hello/zhangsan.html 其中的hello/zhangsan 为配置里面的 'hello/[:name]' 一 一对应,请求方法为get,后缀名为html 符合这个要求后就转交给index/index/hello

还可以直接引用Route类

use think\Route;

Route::rule('hello/:name','index/hello');

2、传递多个参数 设置URL分隔符

在config.php里的,    'pathinfo_depr'          => '-',

http://www.tp5.com/hello-aaa-dd-33.html (短路径)

Array ( [name] => aaa [dd] => 33 )

3、变更规则

http://www.tp5.com/index/index/today/year/2017/month/09

改造成:http://www.tp5.com/today/2017/09.html

在route.php里配置

return [
    'today/[:year]/[:month]' => ['index/index/today',['method'=>'get','ext' => 'html',['year'=>'\d{4}','month'=>'\d{2}']]], //多个参数
];

如果去掉 'ext' =>'html' 那么就对.html没有要求可以不用带就行

echo 今天是2018年10月

4、生成URL地址

对SEO友好的HTML后缀

设置config.php里面的

    'url_html_suffix'        => 'html',

    public function url(){
        
        echo Url::build('url2','a=1&b=2');
        echo '<br>';
        echo url('url2', 'a=1&b=2');
        echo '<br>';
        echo url('url2',['a'=>1,'b'=>'2']);
        echo '<br>';
        echo url('url2',array('a'=>1,'b'=>'2'));
        echo '<br>';
        echo url('admin/index2/url2','a=1&b=2');
        echo '<br>';
        echo url('admin/HelloWorld/hello'); //自动切换 url_convert
        echo '<br>';
        echo url('tody/2018/10'); //路由规则
        echo '<br>';        
    }

输出的结果为:

/index/index/url2/a/1/b/2.html
/index/index/url2/a/1/b/2.html
/index/index/url2/a/1/b/2.html
/index/index/url2/a/1/b/2.html
/admin/index2/url2/a/1/b/2.html
/admin/hello_world/hello.html
/tody/2018/10.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值